39.

prev next contents
monitorenter

enter synchronized region of code

Jasmin Syntax
     monitorenter 
Stack

Before

After
objectref
...
...

Description

The monitorenter/monitorexit mechanism is used by the Java synchronized statement to coordinate access to an object among multiple threads. For example, when you write in Java code:

 static void Sort(int [] array) {     // synchronize this operation so that some other thread can't     // manipulate the array while we are sorting it. This assumes that other     // threads also synchronize their accesses to the array.     synchronized(array) {         // now sort elements in array     } } 
then JVM code like the following is generated:
 .method static Sort([I)V     aload_0     monitorenter    ; lock object in local variable 0      ; now sort elements in array     aload_0     monitorexit      ; finished with object in local variable 0     return .end method 
monitorenter obtains an exclusive lock on the object referenced by objectref. There are three possible scenarios:

If no other thread has locked the object, a new lock is established on the object, and execution continues at the next instruction.

If the object is currently locked by another thread, monitorenter blocks, waiting for the other thread to unlock the object.

If the current thread already owns a lock on the object, a counter is incremented - the lock will only be released when the counter returns to zero (see monitorexit).

Exceptioms

NullPointerException - the object reference on the stack is null.

Bytecode

Type

Description
u1
monitorenter opcode = 0xC2 (194)
See Also

monitorexit

The Java Language Specification provides a full account of how locks and threads are managed.

Notes

1. Methods which are marked as synchronized implicitly perform a monitorenter when invoked, and a monitorexit when they return.

2. Java's wait(), notify() and notifyAll() methods also interact with locks on objects.


prev next contents
Java Virtual Machine, by Jon Meyer and Troy Downing, O'Reilly Associates


Java Virtual Machine
Java Virtual Machine (Java Series)
ISBN: 1565921941
EAN: 2147483647
Year: 1996
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net