Importance of Thread.onSpinWait() method in Java 9?

JavaObject Oriented ProgrammingProgramming

Thread.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. It allows the JVM to issue processor instructions on some system architectures to improve reaction time in such spin-wait loops, and also reduce the power consumed by the core thread. It can benefit the overall power consumption of a java program and allows other core threads to execute at faster speeds within the same power consumption envelope.

Syntax

public static void onSpinWait()

Example

public class ThreadOnSpinWaitTest {
   public static void main(final String args[]) throws InterruptedException {
      final NormalTask task1 = new NormalTask();
      final SpinWaitTask task2 = new SpinWaitTask();
      final Thread thread1 = new Thread(task1);
      thread1.start();
      final Thread thread2 = new Thread(task2);
      thread2.start();
      new Thread(() -> {
         try {
            Thread.sleep(1000);
         } catch(final InterruptedException e) {
            e.printStackTrace();
         } finally {
            task1.start();
            task2.sta*rt();
         }
      }).start();
      thread1.join();
      thread2.join();
   }
   private abstract static class Task implements Runnable {
      volatile boolean canStart;
      void start() {
         this.canStart = true;
      }
   }
   private static class NormalTask extends Task {
      @Override
      public void run() {
         while(!this.canStart) {
         }
         System.out.println("Done!");
      }
   }
   private static class SpinWaitTask extends Task {
      @Override
      public void run() {
         while(!this.canStart) {
            Thread.onSpinWait();
         }
         System.out.println("Done!");
      }
   }
}

Output

Done!
Done!
raja
Published on 31-Mar-2020 14:54:07
Advertisements