Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onSpinWait​() method of Thread class - Java 9

While learning Java 9 features I came across a new method of Thread class, called onSpinWait​. As per javadocs, this method is used for this:

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

Can someone help me understand this method giving a real-life example or scenario?

like image 796
Sachin Sachdeva Avatar asked Jun 19 '17 04:06

Sachin Sachdeva


People also ask

What is thread onSpinWait?

onSpinWait() method has been introduced in Java 9. It is a static method of Thread class and can be optionally called in busy-waiting loops.

What is the run () method of thread class?

The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

What are suspend () and resume () methods of a thread class?

The suspend() method of thread class puts the thread from running to waiting state. This method is used if you want to stop the thread execution and start it again when a certain event occurs. This method allows a thread to temporarily cease execution. The suspended thread can be resumed using the resume() method.


1 Answers

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

It's a very weakened form of yielding: it tells your CPU that you are in a loop that may burn many 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 ready-to-run 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 state.cas(new_value=1, wanted_value=0) == false //if state is 0 (unlocked), store 1 (locked) and return true, otherwise just return false.        yield  routine unlock:     atomic_store(state,0) 

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

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

like image 200
David Haim Avatar answered Sep 18 '22 00:09

David Haim