Reputation: 717
In Java the Object
and Thread
are separate classes. The Java Object
source code doesn't mention anything about monitor / Thread
although we have the wait()
/notify()
methods.
So the question is how does the Object
's monitor knows details of thread which has acquired it ? Where is this information stored ? how are the objects and threads linked ?
Upvotes: 3
Views: 101
Reputation: 34638
Generally speaking, this is implementation-dependent.
The Java code for both Object
and Thread
only does rather superficial stuff. But the real work is done by native methods.
The Java Language Specification specifies how an object monitor and its wait sets are supposed to behave, but it does not specify how this is going to be implemented.
Furthermore, although the Java Virtual Machine has the commands monitorenter
and monitorexit
, the JVM spec says:
The association of a monitor with an object may be managed in various ways that are beyond the scope of this specification. For instance, the monitor may be allocated and deallocated at the same time as the object. Alternatively, it may be dynamically allocated at the time when a thread attempts to gain exclusive access to the object and freed at some later time when no thread remains in the monitor for the object.
The synchronization constructs of the Java programming language require support for operations on monitors besides entry and exit. These include waiting on a monitor (
Object.wait
) and notifying other threads waiting on a monitor (Object.notifyAll
andObject.notify
). These operations are supported in the standard packagejava.lang
supplied with the Java Virtual Machine. No explicit support for these operations appears in the instruction set of the Java Virtual Machine
This all amounts to one thing: How exactly an object is implemented, what's in its header, how its monitor is implemented, and how the wait()
and notify()
methods are implemented are all entirely up to the programmers who wrote the particular JVM. The implementation by Oracle (inherited from Sun) may be completely different than that of IBM or IcedTea.
Furthermore, even for the same programming team, the details of implementations differ between various operating systems for which the JVM is available. The reason for this is clear: the JVM depends on the operating system's threading mechanism to implement its threads, and each operating system offers access to threads in very different ways.
So a programmer who writes a threading implementation for Windows does very different things than one who writes a threading implementation for Linux or MacOS X. The threads may be locked in different ways, so monitors may be completely different between the operating system.
To sum up:
Upvotes: 7