Why wait and notify methods are there in Object instead of Thread class?

Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is the correct place to make them available for every Object if this mechanism is not available via any java keyword like synchronized.
Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication mechanism between two thread

Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

In Java in order to enter a critical section of code, Threads needs lock and they wait for lock, they don’t know which threads hold lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than a thread in Java.

These are just my thoughts on why the wait and notify method is declared in Object class rather than Thread in Java and you have different versions than me. In reality its another design decision made by Java designers like not supporting Operator overloading in Java. Anyway please post if you have any other convincing reason why wait and notify method should be in Object class and not on Thread.

Most important reason is below

In Java all object has a monitor. Threads waits on monitors so, to perform a wait, we need 2 parameters:
– a Thread
– a monitor (any object)

In the Java design, the thread can not be specified, it is always the current thread running the code. However, we can specify the monitor (which is the object we call wait on). This is a good design, because if we could make any other thread to wait on a desired monitor, this would lead to an “intrusion”, posing difficulties on designing/programming concurrent programs. Remember that in Java all operations that are intrusive in another thread’s execution are deprecated (e.g. stop()).”

Popular posts from this blog

Window function in PySpark with Joins example using 2 Dataframes (inner join)

Complex SQL: fetch the users who logged in consecutively 3 or more times (lead perfect example)

Credit Card Data Analysis using PySpark (how to use auto broadcast join after disabling it)