Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any difference if thread is waiting for monitor to be freed before synchronized block or if it calls wait()

I've read many docs about thread states, some of them tells that there is two different states: blocked (before synchronized) and wait (if calls wait), some others are telling that there is only one state: wait. Moreover, some docs telling that you should call notify() for every wait() and if you don't then threads waiting() will never be eligible for execution even if monitor is unlocked.

like image 396
dhblah Avatar asked Dec 08 '22 01:12

dhblah


2 Answers

From you last sentence I see you don't fully understand the difference between synchronized and wait()/notify().

Basically, monitor has lock and condition. It's almost orthogonal concepts.

  • When thread enters a synchronized block, it acquires a lock. When thread leaves that block, it releases a lock. Only one thread can have a lock on a particular monitor.

  • When thread having a lock calls wait(), it releases a lock and starts waiting on its condition. When thread having a lock calls notify(), one of the threads (all threads in the case of notifyAll()) waiting on the condition becomes eligible for execution (and starts waiting to acquire a lock, since notifying thread still has it).

So, waiting to acquire a lock (Thread.State.BLOCKED) and waiting on the monitor's condition (Thread.State.WAITING) are different and independent states.

This behaviour becames more clear if you look at Lock class - it implements the same synchronization primitives as synchronized block (with some extensions), but provides clear distinction between locks and conditions.

like image 128
axtavt Avatar answered Dec 09 '22 14:12

axtavt


There are two different states BLOCKED and WAITING.

The part about waiting forever if no one notifies (or interrupts) you is true.

like image 25
Thilo Avatar answered Dec 09 '22 15:12

Thilo