Java – how to link an object to a thread so that wait() and notify() work
In Java, object and thread are separate classes Although we have wait () / notify () methods, the Java object source code does not mention anything about monitor / thread
So the question is, how does the object monitor know the details of the thread that gets it? Where is this information stored? How are objects and threads linked?
Solution
In general, this is implementation dependent
The Java code of object and thread is only quite superficial But the real work is done through local methods
The Java language specification specifies how the object monitor and its wait set should behave, but it does not specify how to implement it
In addition, although the Java virtual machine has monitorenter and monitorexit commands, the JVM specification says:
It's all the same: the implementation of the object, the content in the title, the implementation of the monitor, and the implementation of the wait () and notify () methods all depend on the programmer who writes the specific JVM The implementation of Oracle (inherited from sun) may be completely different from that of IBM or icedtea
In addition, even for the same programming team, the implementation details vary among the various operating systems available to the JVM The reason is obvious: the JVM relies on the threading mechanism of the operating system to implement its threads, and each operating system provides access to threads in a very different way
Therefore, programmers who write thread implementations for windows are completely different from programmers who write thread implementations for Linux or MacOS X Threads may lock in different ways, so monitors between operating systems may be completely different
To sum up:
>The monitor of the object and the behavior of the wait set of the monitor are defined in the Java language specification. > Thread management depends on the operating system Therefore, it must be implemented at the native level, not in the Java language itself. > The data structure required to save the monitor, the current thread to save the monitor, waiting set, etc. are also at the local level, and may be different between operating systems and JVM implementations. > Oracle's implementation of all these in its own JVM is not necessarily the only correct way, followed by all other implementations