Interview Questions

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

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

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

1. Every Object has a monitor, acquiring that monitors allow thread to hold lock on object. But Thread class does not have any monitors.

2. 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. Now, Straight forward question that comes to mind is how thread acquires object lock by acquiring object monitor? Let’s try to understand this basic concept in detail?

3. Wait(), notify() and notifyAll() method being in Object class allows all the threads created on that object to communicate with other. [As multiple threads may exist on same object].

4. As multiple threads exists on same object. Only one 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, thread having these methods does not make any sense because multiple threads exists on object its not other way around (i.e. multiple objects exists on thread).

5. Now let’s discuss one hypothetical scenario, what will happen if Thread class contains wait(), notify() and notifyAll() methods?
Having wait(), notify() and notifyAll() methods means Thread class also must have their monitor.
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 (because synchronization won't be possible).

(Continued on next question...)

Other Interview Questions