When using a thread to run a task, it’s common to have the task wait for certain condition before it can continue. This is usually done by using busy-waiting with a
volatile variable as the flag. This flag is set by another thread to stop the waiting. Before Java 9, we use an empty loop to wait for the condition. The new static method
onSpinWait() of class
Thread in Java 9 can make the waiting more efficient.
The code below shows an example of
SpinWaitTask both use the
volatile boolean variable
canStart as the flag. The flag is set to
true using the method
start(). The different of these two classes is that
Thread.onSpinWait() in the loop. Here we use another thread to call the method
start() after 3 seconds to stop the waiting. After running the code, you should see two
Done! outputs in the console. It’s recommended to use
Thread.onSpinWait to improve the performance.
Check out the book Exploring Java 9 for more new features in Java 9.