5

In Java Concurrency in Practice, the authors write:

When locking is contended, the losing thread(s) must block. The JVM can implement blocking either via spin-waiting (repeatedly trying to acquire the lock until it succeeds) or by suspending the blocked thread through the operating system. Which is more efficient depends on the relationship between context switch overhead and the time until the lock becomes available; spin-waiting is preferred for short waits and suspension is preferable for long waits. Some JVMs choose between the two adaptively based on profiling data of past wait times, but most just suspend threads waiting for a lock.

When I read this I was quite surprised. Are there any known JVMs implementing blocking either on always spin-waiting or sometimes spin-waiting due to profiling results? It's hard to believe for now.

Konrad Reiche
  • 27,743
  • 15
  • 106
  • 143
  • I don't know about use in JVMs specifically, but Windows implements adaptive spinlocks on multi-core systems for `CRITICAL_SECTION` objects. – clstrfsck Jun 13 '11 at 01:24
  • yes, all of them as far as i know, the normal synchronized keyword uses a spinlock to modify the waiters. there are impl that can have spinning for seconds (provided you get enough cores, that's ok) – bestsss Jun 13 '11 at 10:28

2 Answers2

5

Here is evidence that JRockit can use spinlocks - http://forums.oracle.com/forums/thread.jspa?threadID=816625&tstart=494

And if you search for "spin" in the JVM options listed here you will see evidence for the use of / support for spinlocks in Hotspot JVMs.

And if you want a current example, look at "src/hotspot/share/runtime/mutex.cpp" in the OpenJDK Java 11 source tree.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    The JVM options list has moved: http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html – Ted Graham Jan 31 '12 at 15:01
3

What the authors have written is right and it only makes sense. This is true for Linux as well. The rationale of why spin locks are used is because most resources are protected for a fraction of a millisecond. As such, to suspend, push all the contents of the registers onto the stack and relinquish CPU is just way too much overhead and not worth it. Thus even though it just spins in a tight set of instructions, sometimes just wasting time, it is still way more efficient than swapping out.

That being said, with the VM profiling, it would ideally make your processing more efficient. As such, is there are particular case that you always want to suspend? Or maybe always spin-wait?

Vern
  • 2,393
  • 1
  • 15
  • 18
  • I'm not familiar with Java, but out of curiosity is it possible for the programmer to force suspension or force spin waiting, instead of allowing the JVM to adaptively choose? – CMCDragonkai May 30 '15 at 05:57