Show Stopper Show Stopper - 4 months ago 28
Java Question

onSpinWait​() method of Thread class - Java 9

While learning

I come across a new method of
Thread Class
called onSpinWait​(). According to java docs this method is used to :

Indicates that the caller is momentarily unable to progress, until the
occurrence of one or more actions on the part of other activities.

I tried to understand it, but was unable to grasp.I also googled it but unable to find some practical scenarios where it can be used.

Can some one help me understand this method giving real life example.

Answer Source

It's the same (and probably compiles to) the x86 opcode PAUSE and equivilant the Win32 macro YieldProcessor, GCC's __mm_pause() and the C# method Thread.SpinWait

It's a very weakened form of yielding: it's about telling your CPU that you are in a loop that may burn some quite CPU-cycles waiting for something to happen (busy-waiting).

This way, The CPU can assign more resources to other threads, without actually loading the OS scheduler and dequeuing a sleeping thread (which may be expensive).

a common use for that is spin-locking, when you know the contention on a shared memory is very infrequent or finishes very quickly, a spinlock may preform better than an ordinary lock.

Pseudo code for such can look like:

int state = 0; //1 - locked, 0 - unlocked

routine lock:
    while cas(state, 1) == 1

routine unlock:

yield can be implemented in terms of Thread.onSpinWait(), hinting that while trying to lock the lock, the CPU can give more resources to other threads.

PS. this technique of yielding is extremely common and popular when implementing a lock-free algorithms, since most of them depends on busy-waiting (which is implemented almost always as an atomic CAS loop). this has every real-world use you can imagine.