Why does a compiler complaint complain about the wait used in an unsynchronized block

As far as I know, when we want to call waitin java, we need to synchronize the API / block else, and at runtime it will be IllegalMonitorStateException. My question is, since we are sure that it always throws an exception, why doesn't the compiler complain about this?

+4
source share
5 answers

Because you may have called a method with waitin a synchronized block somewhere higher in the call stack. The compiler can only find the syntactic validity of your code - it cannot check for logical errors.

+3
source

. . , .

+1

KDM : - . , , :

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

}

, synchronized .

+1

wait() , . throws, , .

0

:

  • - ,
  • developing a compiler that would handle all possible trivial errors would take too much time and energy
  • such compilers would not be popular because it would take them forever to compile
-2
source

All Articles