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 ?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How much of a burden is that?
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.
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.

Comments

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.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.