Tuesday, 28 February 2017

Why wait(), notify() and notifyAll() are in Object class and not in Thread class in java?

1. These method not only used for synchronization, but also they can be used for communication between two threads and Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized.

Point to remember: Synchronized is used to provide mutual exclusion and ensuring thread safety of Java class like race condition. However wait, notify and notifyAll can be used for communication mechanism among threads.

2. Every Object has a monitor, acquiring that monitors allow thread to hold lock on object (=Locks are made available on per Object basis), which is another reason wait and notify is declared in Object class rather than Thread class.

3. wait(), notify() and notifyAll() are called on objects only When wait() method is called on object by thread it waits for another thread on that object to release object monitor by calling notify() or notifyAll() method on that object.
When notify() method is called on object by thread it notifies all the threads which are waiting for that object monitor that object monitor is available now.
So, this shows that wait(), notify() and notifyAll() are called on objects only.

4. As multiple threads may request to access the same object at a time. However only thread can hold object monitor at a time. As a result thread can notify other threads of same object that lock is available now. But, put these method into thread does not make any sense because multiple threads exists on object it's no other way around (i.e. multiple objects exists on thread).

Hypothetical scenario:
Suppose, Thread class contains wait(), notify() and notifyAll() methods?
Having wait(), notify() and notifyAll() methods means Thread class must have their monitor i.e. every thread having their monitor will create few problems:

Thread communication problem

Synchronization on object won’t be possible- Because object has monitor, one object can have multiple threads and thread hold lock on object by holding object monitor. But if each thread will have monitor, we won’t have any way of achieving synchronization.

Inconsistency in state of object (=synchronization won't be possible).

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...