The busy waiting technique (also known as busy-looping or spinning) consists of a loop that checks a condition (typically, a flag condition). For example, the following loop waits for a service to start:
private volatile boolean serviceAvailable;
...
while (!serviceAvailable) {}
Java 9 introduced the Thread.onSpinWait() method. This is a hotspot that gives the JVM a hint that the following code is in a spin loop:
while (!serviceAvailable) {
Thread.onSpinWait();
}
Intel SSE2 PAUSE instruction is provided precisely for this reason. For more details, see the Intel official documentation. Also have a look at this link: https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops.
If we add this while loop in a context, then we obtain the following class:
public class StartService implements Runnable {
private volatile boolean serviceAvailable;
@Override
public void run() {
System.out.println("Wait for service to be available ...");
while (!serviceAvailable) {
// Use a spin-wait hint (ask the processor to
// optimize the resource)
// This should perform better if the underlying
// hardware supports the hint
Thread.onSpinWait();
}
serviceRun();
}
public void serviceRun() {
System.out.println("Service is running ...");
}
public void setServiceAvailable(boolean serviceAvailable) {
this.serviceAvailable = serviceAvailable;
}
}
And, we can easily test it (do not expect to see the effect of onSpinWait()):
StartService startService = new StartService();
new Thread(startService).start();
Thread.sleep(5000);
startService.setServiceAvailable(true);