Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does wait / notify work at the JVM level?

Wait and notify seem like messages that are passed between threads, if this is true there must be queues for buffering these messages. If so then there must be atomic operations for adding messages to and removing message from the queue, also there must be a helper thread for each Java thread that listens for these messages?

Would be great to hear your thoughts.

like image 678
newlogic Avatar asked Oct 08 '13 12:10

newlogic


1 Answers

Wait and notify seem like messages that are passed between threads,

They are really not messages. When a thread calls wait() it puts itself in the wait queue associated with the particular object monitor. When another thread calls notify() it pulls the first thread (if any) out of the queue and places it in the "run" queue. It is about changing in thread state and putting a thread in a queue not messages between threads.

If so then there must be atomic operations for adding messages to and removing message from the queue

Most likely there are not atomic operations around message queues but there are certainly atomic operations around testing/setting memory locations which help gain locks and resolve other thread contention.

there must be a helper thread for each Java thread that listens for these messages?

There is certainly not a helper thread for each Java thread. As Java threads transition from one state to another or are time sliced, they have as associated OS thread that maintains its state and does all of the messaging and signaling. With most (if not all) implementations also having the OS and hardware which takes care of the thread scheduling leaving the JVM native code to do the Java accounting.

like image 54
Gray Avatar answered Oct 02 '22 04:10

Gray