- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Importance of Thread.onSpinWait() method in Java 9?
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!
Advertisements