3

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 ?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Dharik
  • 43
  • 1
  • 4
  • possible duplicate of [Why are wait() and notify() declared in Java's Object class?](http://stackoverflow.com/questions/1769489/why-are-wait-and-notify-declared-in-javas-object-class) – gnat Jan 09 '13 at 11:08

4 Answers4

4

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.

Daniel
  • 27,718
  • 20
  • 89
  • 133
  • 1
    How much of a burden is that? – Erick Robertson Mar 01 '12 at 12:18
  • 1
    Each object carries a 8 byte header. If we wouldn't have to be able to sync on objects, a 4 byte header (the class ref) might imho be enought. However, I don't know if some bytes of the extra header are still needed for GC, but this info might also still be embedded into the 4 byte header. – Daniel Mar 01 '12 at 12:21
4

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

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.

Konstantin Solomatov
  • 10,252
  • 8
  • 58
  • 88
0

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?

OGHaza
  • 4,795
  • 7
  • 23
  • 29
Paramesh Korrakuti
  • 1,997
  • 4
  • 27
  • 39