Reputation: 20006
If we call wait()
, notify()
or notifyAll()
on an object without a synchronized
block, we get an IllegalMonitorStateException
at runtime.
Why doesn't the compiler flag me if I try to call these methods without a synchronized block?
Upvotes: 4
Views: 319
Reputation: 6718
It's not possible to prove that a method further up the stack didn't already obtain the monitor.
For example:
class Foo
{
void foo()
{
synchronized (bar)
{
bar.bar();
}
}
}
class Bar
{
void bar()
{
this.wait();
}
}
Would be legal (assuming bar
is an instance of Bar
), but impossible to prove that there are is no code that calls bar
without first obtaining the monitor.
Upvotes: 1
Reputation: 1717
As the execution from one thread to another thread always change at run-time, and you can thing of producer-consumer problem the problem cannot be simulate at compile time, because consumer is consuming the buffer once the buffer is consumed it notifies to producer at that time and till that time producer will wait otherwise there is exception,so the whole logic of these methods is inside synchronized blocks
Upvotes: 0
Reputation: 21764
Calling those methods only requires that the current thread be the owner of the object`s monitor. However, that could mean calling a method without synchronized from within 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);
}
In general, there is now way to know at compile time whether any piece of code will be executed when the current thread does not hold a particular monitor, which is likely why the compiler does not even try to flag this.
Upvotes: 8