Sachin
Sachin

Reputation: 3544

Why compiler doent complain for wait used in non-synchronised block

As far as I know when we want to call wait in java, we need to synchronize API/block else it will end up in IllegalMonitorStateException at run time. My question is, as we are so sure its always result in exception, why compiler doesn't complain about it?

Upvotes: 4

Views: 146

Answers (4)

Gurunath
Gurunath

Reputation: 1

wait() is part of object class, hence we can call it directly. In threads, there is nothing similar to throws clause to indicate compiler that method should be surrounded by synchronized block.

Upvotes: 0

Marco13
Marco13

Reputation: 54629

As KDM mentioned in his answer: The synchronization might have taken place somewhere higher in the call stack. And as an intuitive example for a case where it simply is not possible to detect whether the call is legal or not:

class Example
{
    private final Object lock = new Object();

    private void run() throws InterruptedException
    {
        if (Math.random() > 0.5)
        {
            synchronized (lock)
            {
                doWait();
            }
        }
        else
        {
            doWait();
        }
    }

    private void doWait() throws InterruptedException
    {
        lock.wait();
    }

}

You simply do not know whether the call happens from inside the synchronized block or not.

Upvotes: 1

user207421
user207421

Reputation: 310875

No compiler could detect this error. It isn't a static semantic of the language. It isn't a semantic of the language at all, actually, it is a semantic of the runtime library.

Upvotes: 1

Dakshinamurthy Karra
Dakshinamurthy Karra

Reputation: 5463

Because you may have been calling the method that has wait in a synchronised block somewhere higher up in the call stack. Compiler can find only the syntactic validity of your code - it can't check for logical errors.

Upvotes: 3

Related Questions