|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 3 of 3
Two opcodes, monitorenter and monitorexit, are used for synchronization blocks within methods, as shown in the table below.
|
|
|
|
|---|---|---|
monitorenter |
|
pop objectref, acquire the lock associated with objectref |
monitorexit |
|
pop objectref, release the lock associated with objectref |
When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If
the thread already owns the lock for that object, a count is incremented. Each time monitorexit is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.
Take a look at the bytecode sequence generated by the reverseOrder() method of the KitchenSync class.
Note that a catch clause ensures the locked object will be unlocked even if an exception is thrown from within the synchronized block. No matter how the synchronized block is exited, the object lock acquired when the thread entered the block definitely will be released.
To synchronize an entire method, you just include the synchronized keyword as one of the method qualifiers, as in:
class HeatSync {
private int[] intArray = new int[10];
synchronized void reverseOrder() {
int halfWay = intArray.length / 2;
for (int i = 0; i < halfWay; ++i) {
int upperIndex = intArray.length - 1 - i;
int save = intArray[upperIndex];
intArray[upperIndex] = intArray[i];
intArray[i] = save;
}
}
}
The JVM does not use any special opcodes to invoke or return from synchronized methods. When the JVM resolves the symbolic reference to a method, it determines whether the method is synchronized. If it is, the JVM acquires a lock before invoking the method. For an instance method, the JVM acquires the lock associated with the object upon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized method completes, whether it completes by returning or by throwing an exception, the lock is released.
Read more about Core Java in JavaWorld's Core Java section.
Read more of Bill's Under the Hood columns on JavaWorld
More about threads and concurrency
Inside the Java Virtual Machine (Bill Venners, McGraw-Hill Companies, January 2000) is reprinted in select chapters by Artima.com.
Also check out the JavaWorld site map and search engine.