0

I am trying to synchronize different threads in my application. Basically there are some threads that should be able to block the application from closing. Here is what I have:

public class Test{
  public static void main(String args[]){
    Syncer syncer = new Syncer();
    Object o = new Object();
    syncer.lockExit(o);
    //.. do some stuff//
    syncer.unlockExit(o);
  }
}

public class Syncer {

    private List<Object> l_Exit;

    public Syncer() {
        l_Exit = new ArrayList<Object>();
    }

    public synchronized void lockExit(Object o) {
        l_Exit.add(o);
    }

    public synchronized void unlockExit(Object o) {
        l_Exit.remove(o);
        if (l_Exit.isEmpty()) {
            l_Exit.notifyAll();
        }
    }

    public synchronized void waitForExit() {
        while (!l_Exit.isEmpty()) {
            try {
                l_Exit.wait();
            } catch (InterruptedException ex) {
                Test.log.log(Level.SEVERE, null, ex);
            }
        }
    }
}

I get IllegalMonitorException when running syncer.unlockExit(o);

black
  • 357
  • 3
  • 18

1 Answers1

0
public synchronized void unlockExit(Object o) {
    l_Exit.remove(o);
    if (l_Exit.isEmpty()) {
        l_Exit.notifyAll();
    }
}

You need to be in a synchronized block in order for Object.wait(), Object.notify() or Object.notifyAll() to work.

public synchronized void unlockExit(Object o) {
     synchronized (lock) {
        l_Exit.remove(o);
        if (l_Exit.isEmpty()) {
          l_Exit.notifyAll();
        }
     }
}

See this question for clarification so as to why.

Community
  • 1
  • 1
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Hmm after changing the waitForExit() method I got a warning from netbeans. Is this code correct? public synchronized void waitForExit() { synchronized (l_Exit) { while (!l_Exit.isEmpty()) { try { l_Exit.wait(); } catch (InterruptedException ex) { CakeLauncher.log.log(Level.SEVERE, null, ex); } } } } – black Aug 22 '13 at 15:54