Dharik
Dharik

Reputation: 43

Why wait ,notify and notifyAll Methods are in Object Class?

i know that wait() method always written in synchronized method/block and make lock on Object but i want to only know that what problem is arise at that time when this all methods are in Thread class ?

Upvotes: 3

Views: 7070

Answers (4)

Paramesh Korrakuti
Paramesh Korrakuti

Reputation: 2067

These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.

The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.

For more explanation read: Why wait() ,notify() and notifyAll() methods are in Object class instead of Thread class?

Upvotes: 0

Konstantin Solomatov
Konstantin Solomatov

Reputation: 10352

These method's context is a lock associated with every object in Java so we can't move them to the Thread class. For example we might do something like this. Thread 1 adds an item to a list and notifies other threads about it. Thread 2 waits for a list update and does something with it:

thread 1
synchronized (lock) {
    list.add(item);
    lock.notifyAll();     
}

thred 2 
synchronized (lock) {
    list.wait();
    ... do something with list
}

If these methods were moved to a thread, the thing we done here would be impossible.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533710

The problem with using them on a Thread object is that the Thread uses this lock for it own purposes. This is likely to lead to confusion and odd bugs.

Upvotes: 4

Daniel
Daniel

Reputation: 28084

They are also in the Thread class. But a thread instance here is equally well suited as a synchronization object as any other object.

In addition, there have already been voices that question this decision of sun, since now every object carries the burden to be able to be synchronized on, and IMHO they should have refactored this out to separate objects long ago.

If I need to have something to synchronize on, I often do:

private Object syncObject = new Object();

Then I can do my

synchronized(syncObject) 

everywhere in the code and do not have to bother with anyone else accidentially synchronizing on this.

Upvotes: 4

Related Questions