unmaskableinterrupt
unmaskableinterrupt

Reputation: 408

after a thread calls notify what happens?

If I have T1 T2 T3 all have called wait and are in the waitset, if t4 calls notify, as I understand it - one of T1,T2 or T3 will be notified and will possibly reacquire the lock and return from wait. What happens to the threads that don't receive the notify ? Will they still be in the waitset ? Do they have to be notified again to return from wait() ?

If T4 calls notify all, only one of t1 T2 T3 will return from wait, after acquiring lock. In this case, since all of T1T2 and T3 have received notify, will they automatically try to acquire the lock and one by one return from wait ?

Upvotes: 2

Views: 1746

Answers (4)

arun_suresh
arun_suresh

Reputation: 2925

What happens to the threads that don't receive the notify ? Will they still be in the waitset ? Do they have to be notified again to return from wait() ?

Yes, they remain in the wait set. A notify must be sent to each of the waiting threads. On receipt of a notify, a waiting thread will try to re-acquire the lock

If T4 calls notify all, only one of t1 T2 T3 will return from wait, after acquiring lock. In this case, since all of T1T2 and T3 have received notify, will they automatically try to acquire the lock and one by one return from wait ?

The is no guarantee in the order in which T1, T2 and T3 will act on the notify signal. But yes, all of them will try to re-acquire the lock at the same time (Only one will succeed and return from the wait call)

Make sure you put the wait within a while loop to recheck the condition once the waiting thread has returned from a wait() call.

This link gives a good overview of when to use notify()/notifyAll()

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533520

When a thread performs notify() another thread cannot acquire the lock until it has released it. In you want to wake all threads use notifyAll().

Whatever you are doing I would suggest you ensure the Concurrency Library in Java does do it for you already before you attempt to write low level wait/notify code.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500535

For notify(), the other threads will still be waiting for another notify() call.

For notifyAll(), the other threads will just be waiting to acquire the lock, one at a time - no more notify calls are required. (They'll need to wait for the notifying thread to release the lock first of course.)

Upvotes: 2

LordDoskias
LordDoskias

Reputation: 3191

The thread is put into RUNNABLE and not RUNNING state. This means that notify()`ing a thread doesn't necessarily means it will run immediately. So it's up to the scheduler to decide what is going to be run next out of the pool of RUNNABLE threads.

Upvotes: 3

Related Questions