Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is it efficient to use Thread.sleep(1) for an idle thread?

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.

like image 697
AutoBotAM Avatar asked Mar 14 '12 16:03

AutoBotAM


1 Answers

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();
    }
  }
}
like image 93
Mike Samuel Avatar answered Nov 15 '22 17:11

Mike Samuel