You can only legally call wait(), notify(), or notifyAll() on an object if you hold the lock on that object -- i.e., inside a synchronized method called on that object, or a synchronized block locked on that object.

If you have no idea what I'm talking about, then you probably want to call the static "sleep" method of the Thread class, anyway, rather than wait().

Originally posted by faisal usmani: Why is it necessary to have a lock on that object , if we are calling wait , notify or notifyAll method on that object .

Because wait() and notify() are the mechanism by which different Threads communicate in Java. The lock, or "monitor", is the mechanism by which Threads communicate. You lock the object and then call wait(), which puts the calling thread to sleep until some other thread calls notify() on that same object.

I'm going to move this to our "Threads and Synchronization" forum for further discussion.

faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139

posted Feb 06, 2006 08:41:00

0

Thanks sir i got the point , shall be really grateful if i can get a more elaborate detail on it .

Originally posted by faisal usmani: Thanks sir i got the point , shall be really grateful if i can get a more elaborate detail on it .

Unfortunately, this is not something that you can learn in paragraph. But it goes something like this.

- wait(), notify(), notifyAll() by itself is not very useful. It is a notification tool, but it needs to have something to notify about. It could be a simple as a state flag -- to as complex as a full database.

- since this data/flags are being accessed by multiple threads, some sort of synchronization is necessary. However, this synchronization needs to be unlocked during the wait. In other words, we need to lock the data, mark the data that we need to wait for, unlock the data, and then wait.

- Unfortunately, there is a race condition between "unlock the data" and "wait". (There is also another issue with multiple grabs of locks) In order to solve this, the lock is actually freed by the wait() method -- which means that it must actually be held when wait() is called.

One other point, this is *not* a feature that is specific to Java. Condition Variables in Solaris threads, POSIX threads, and Windows threads all require that a lock, mutex, or critcal section be held. It also does the same thing, it frees the mutex while performing the CV_wait (in a fashion that does not have a race condition) and grabs it back, prior to returning from the wait.

Henry

faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139

posted Feb 06, 2006 09:17:00

0

Thanks Henry ,

It is really of great help , since i am a newbie in Java . I thought wait , notify , notifyAll are related to objects (of Object class) only . That is why couldn't figure out the exception in the above code