I have a main loop in my thread, and part of it tests for if an idle boolean is true. If it is, it will call Thread.sleep(1)
upon each iteration of the loop. Is this an efficient way to go about doing this? My goal is for the thread to take minimal CPU usage when idle.
No. Use Object.wait
instead and make sure you synchronize on the object containing the boolean. If you don't synchronize and the boolean
is not volatile
, you have no memory barrier so there is no guarantee that the polling thread will see the change to the boolean
.
According to the javadoc:
This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:
- Some other thread invokes the
notify
method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.- Some other thread invokes the
notifyAll
method for this object.- Some other thread interrupts thread T.
- ...
so the thread will take no CPU while it is waiting to be notified.
The code below is a simple idle flag with a waitUntilIdle
method that your main
method can call and a setIdle
method that can be called by another thread.
public class IdleFlag {
private boolean idle;
public void waitUntilIdle() throws InterruptedException {
synchronized (this) {
while (true) {
// If the flag is set, we're done.
if (this.idle) { break; }
// Go to sleep until another thread notifies us.
this.wait();
}
}
}
public void setIdle() {
synchronized (this) {
this.idle = true;
// Causes all waiters to wake up.
this.notifyAll();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With