Christian O.
Christian O.

Reputation: 552

why does this code throw a IllegalMonitorStateException?

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();
}

Upvotes: 2

Views: 134

Answers (1)

SLaks
SLaks

Reputation: 888177

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

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

Upvotes: 6

Related Questions