Interview Questions

What is busy spin?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

53. What is busy spin?

What is busy spin?
When one thread loops continuously waiting for another thread to signal.

Performance point of view - Busy spin is very bad from performance point of view, because one thread keeps on looping continuously ( and consumes CPU) waiting for another thread to signal.

Solution to busy spin -
We must use sleep() or wait() and notify() method. Using wait() is better option.

Why using wait() and notify() is much better option to solve busy spin? Because in case when we use sleep() method, thread will wake up again and again after specified sleep time until boolean variable is true. But, in case of wait() thread will wake up only when when notified by calling notify() or notifyAll(), hence end up consuming CPU in best possible manner.

Program - Consumer Producer problem with busy spin
Consumer thread continuously execute (busy spin) in while loop till productionInProcess is true. Once producer thread has ended it will make boolean variable productionInProcess false and busy spin will be over.

while(productionInProcess){
System.out.println("BUSY SPIN - Consumer waiting for production to get over");
}

(Continued on next question...)

Other Interview Questions