Using Busy Spinning as Wait Strategy in Java
Busy Spinning is a wait strategy in which one thread waits for some condition to happen which is to be set by some other thread. Here the waiting thread loops continuously without releasing the CPU cycles. This leads to bad performance as the CPU cycles are wasted by a waiting thread.
A classic use case that fits this strategy very naturally is the producer-consumer problem. The producer thread adds items to a queue. The consumer thread waits until an item is produced by the producer before consuming items from the queue. The consumer thread while waiting holds the CPU cycles and thus there is wastage of CPU resources which can be used for some other processing by other threads.
Another example to better understand this strategy is to consider a customer ordering pizza from a Pizza counter. After placing an order, the customer keeps asking the person at the counter if his order is ready every 5 seconds. Here, the customer waiting for this order can utilize his time doing other activities like talking to his friends, browsing the latest news, and so on, instead of busy spinning on the status check of his pizza order.
Pizza order in progress Making pizza customerThread:-Pizza order complete?? --Busy Spinning--- customerThread:-Pizza order complete?? --Busy Spinning--- customerThread:-Pizza order complete?? --Busy Spinning--- Making of pizza with base :thick crust base and toppings as [tomato, corn, cheese, olive] is complete :- pizzaMakerThread Received the ordered pizza:-customerThread Base of the pizza is : thick crust base Toppings are : [tomato, corn, cheese, olive]
In this example, we have 2 classes that implement the Runnable interface. When the PizzaMaker constructor is invoked, it sets the boolean variable isInProgress as true, which means that it has received the pizza order and making of pizza is in progress. In run() it invokes the pizza’s make(). Once pizza is made, it sets the isInProgress boolean variable to false. The Customer thread does a busy spin by looping continuously inside the while loop checking for the status of the order through the boolean variable isInProgress. When the PizzaMaker class sets this variable to false, the customer thread continues with further processing. A better approach would be to implement the wait, notify, and notifyAll() methods from the Object class. The thread waiting for a condition to be satisfied will release CPU resources and perform some other tasks. When some other thread sets this condition for which the thread was waiting, it notifies the waiting thread through notify() method.