Then, they asked why is design like wait
, notify
, and notifyAll
are methods on the Object
class. Why doesn't Java have an interface and these methods are in that interface and which ever class wants to implement it can use it.
All of these methods are implemented in native code and they integrate closely with the synchronized
block that wraps them. They are part of the Java language definition and have specific behaviors that programmers rely on. It would not be appropriate for them just to be interface methods that any object would implement.
When one object calls obj.wait();
on another object, it doesn't have to worry about the implementation of wait
. It needs to make sure that it has a mutex lock on that object so it can make critical updates to it or other storage and if the wait
method was implemented by the object itself, then that object could violate the language requirements and, for example, allow multiple threads into the protected block at the same time. A thread can synchronize
and call wait
/notify
/notifyAll
on another object or not without having to worry about whether or not that object has implemented those methods appropriately. By making them final
methods on Object
the behavior will work the same regardless of the object type or local implementation.
Also, as I mentioned, wait
/notify
/notifyAll
are integrated closely with the surrounding synchronized
block. When a thread is blocked in wait()
the surrounding synchronized
lock is released so that other threads can get access to the protected block. This coordination would not be possible if the wait()
was just a simple method call without other strange language features.
This reminds me of my other answer here: Concept behind putting wait(),notify() methods in Object class