Why are wait
, notify
and notifyAll
methods placed in Object
, not in some separated class?
Note, this question is not about moving them to Thread
class, I just wonder why does they litter Object
, not some new Monitor
class.
I see the following shortcomings of that idea:
this
and <MyClass>.class
become not valid monitors. So we could move away 5 methods from every object with a little woe. Or not?
The real answer is that it was a mistake, finally acknowledged with the creation of the Condition
class, which does exactly what you'd expect. (Although since it is an object, there is a possibility that you'll accidentally invoke wait()
on it instead of await()
, with hilarious consequences...)
Apart from the things you've already listed, tying a monitor to every single object also makes it impossible to have truly immutable objects in Java.
So you can do this for example:
class A {
void foo() {
synchronized((Integer)42) {
...
}
}
}
class B {
void foo() {
synchronized((Integer)42) {
...
}
}
}
Returning the same boxed integer for 42
every time shouldn't be a problem if the object was immutable. But it isn't, it has a mutable state: its monitor, making this kind of synchronization possible. What's particularly evil in this is that you've created a mutex between two pieces of code that on the face of it appear to be independent.
One advantage of this is that you can simply synchronize on a reference without creating a redundant monitor for it:
synchronized (myList) {
myList.add(0);
}
vs
private final Object mySpecialMonitor = new Object();
syncronized(mySpecialMonitor) {
myList.add(0);
}
It would not work if all synchronization was in a separate class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With