Why doesn't it call wait (), notify () or notifyAll () without a synchronized block, and not a compiler error?

If we call wait(), notify()or an notifyAll()object without a block synchronized, we get IllegalMonitorStateExceptionat runtime.

Why doesn't the compiler tell me if I'm trying to call these methods without a synchronized block?

+4
source share
3 answers

Calling these methods requires the current thread to be the owner of the object’s monitor. However, this may mean calling the method without synchronization from the context of another synchronized block.

For example:

public void doWait(Object o) {
    o.wait(); // you would like the compiler to flag this
}

// but in this case it is valid
synchronized(this)
{
    doWait(this);
}

, , - , , , , .

+7

, , , .

:

class Foo 
{ 
  void foo() 
  { 
    synchronized (bar) 
    { 
      bar.bar(); 
    }
  }
}

class Bar 
{ 
  void bar() 
  { 
    this.wait(); 
  } 
}

(, bar bar), , , bar .

+1

Since the execution from one thread to another thread always changes at runtime, and you can solve the problem of the producer-consumer, the problem cannot be simulated at compile time, since the consumer consumes the buffer after the buffer is consumed, it notifies the producer at that time and before at that time, the manufacturer will wait differently, there is an exception, so the whole logic of these methods is inside synchronized blocks

0
source

Source: https://habr.com/ru/post/1527194/


All Articles