Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Empty while loop

I'm making a program with while loops that execute in this manner:

  1. Main thread enters a while loop.
  2. Nothing happens in the while loop.
  3. Thread will stay in the while loop until the condition is satisfied.
  4. Another thread runs a function that will satisfy said condition.

Here is an example:

while(path != null);

There's another function in the class that will set the path to null, and once that happens the main thread should exit this loop. The other function is called in another thread.

However, the main thread does not exit the loop even when path is set to null. Any suggestions?

CODE:

try 
 { 
  for (Node n:realpath) 
    { 
      Thread.sleep(100); 
      actor.walk(n); 
     }
    Thread.sleep(100); 
 } 
 catch (InterruptedException ex) 
  { 
    Logger.getLogger(VNScreen.class.getName()).log(Level.SEVERE, null, ex); 
  } 
  realpath.clear(); 
  path = null;

if(path == null)
    System.out.println("NULLED PATH");
like image 228
Abraham Miguel Espiritu Avatar asked Dec 07 '11 02:12

Abraham Miguel Espiritu


1 Answers

Busy waits are very expensive. I'd do it this way:

Object LOCK = new Object(); // just something to lock on

synchronized (LOCK) {
    while (path != null) {
        try { LOCK.wait(); }
        catch (InterruptedException e) {
            // treat interrupt as exit request
            break;
        }
    }
}

Then when you set path to null, just call

synchronized (LOCK) {
    LOCK.notifyAll();
}

(You can just synchronize on this if both pieces of code are in the same object.)

like image 97
Ted Hopp Avatar answered Oct 07 '22 15:10

Ted Hopp