2

Please explain to me why my code throws a IllegalMonitorStateException at the wait function, as far as I know this only happens if its not done in a synchronized part?

private void deliver(int target) {
    Warehouse targetW = targets[target];
    targetW.deliver();
    System.out.println(name + " starts to deliver too " +
                       targetW.getName());
    int sleepTime = DELIVERY_TIME / LOADING_CAPACITY;
    int counter = 0;
    while (counter < LOADING_CAPACITY) {
        synchronized (targetW) {
            while (!targetW.fill(1)) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        counter++;
        try {
            sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    leaveMSG(targetW);
    targetW.delivered();
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Christian O.
  • 514
  • 1
  • 5
  • 20
  • This is perhaps one of the downfalls of every object having an intrinsic lock. Errors like this aren't caught. I still say there should be a specific class called "Lock" to be used for all locks – Cruncher Dec 02 '13 at 20:52
  • sounds like a Semaphore to me. I am using them too but in this case its more complicated to use for a reason that exceeds the use of this function. – Christian O. Dec 02 '13 at 21:13
  • 1
    possible duplicate of [IllegalMonitorStateException on wait() call](http://stackoverflow.com/questions/1537116/illegalmonitorstateexception-on-wait-call) – Gray Dec 02 '13 at 21:33
  • @Gray That doesn't look like a duplicate. OP: `as far as I know this only happens if its not done in a synchronized part`. He knew this. His problem was a little more specific in that he forgot to specify the object. The answer to it however, is helpful to this, but the question itself is not a duplicate. – Cruncher Dec 02 '13 at 21:36
  • The question is the same but this answer is much better: http://stackoverflow.com/a/1537400/179850 – Gray Dec 02 '13 at 21:40

1 Answers1

6

You can only call wait() inside a synchronized block on that object.

Inside synchronized (targetW), you can call targetW.wait().

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964