Thread.sleep() vs Thread.onSpinWait

Tirafesi :

I have a spin-wait loop that is busy-waiting for a flag to be set. However, it can take a lot of time for that to happen - minutes, or even hours.

Would Thread.sleep() be more efficient than Thread.onSpinWait​()?

tevemadar :

So you wanted to see a short example about Object and its long-available wait() and notify/All() methods? (They are already there in JLS 1.0, from 20+ years ago)

Say no more:

public class NotifyTest {
  private boolean flag = false;
  public synchronized boolean getFlag() {
    return flag;
  }
  public synchronized void setFlag(boolean newFlag) {
    flag = newFlag;
    notifyAll();
  }

  public static void main(String[] args) throws Exception {
    final NotifyTest test = new NotifyTest();

    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.printf("I am thread at %,d, flag is %b\n",
                          System.currentTimeMillis(), test.getFlag());
        synchronized (test) {
          try {
            test.wait();
          } catch (InterruptedException ie) {
            ie.printStackTrace();
          }
        }
        System.out.printf("I am thread at %,d, flag is %b\n",
                          System.currentTimeMillis(), test.getFlag());
      }
    }).start();

    System.out.printf("I am main at %,d, flag is %b\n",
                      System.currentTimeMillis(), test.getFlag());
    Thread.sleep(2000);
    test.setFlag(true);
    System.out.printf("I am main at %,d, flag is %b\n",
                      System.currentTimeMillis(), test.getFlag());
  }
}

If your wait loop has anything else to do, Object.wait() has variants with timeout too.

So objects can be wait()-ed on and then waiting threads can be notified (one of the waiters via notify() or all of them via notifyAll()), and they do not even have to know about each other.
As both waiting and notifying has to happen inside a synchronized block, it is safe and possible to start the block, check the variable/flag/anything, and issue the wait conditionally (just these constructs are not shown here).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112886&siteId=1