Java Reference
In-Depth Information
The expression expr must evaluate to an object reference. After the
lock is obtained, the statements in the block are executed. At the end of
the block the lock is releasedif an uncaught exception occurs within the
block, the lock is still released. A synchronized method is simply a syn-
tactic shorthand for a method whose body is wrapped in a synchronized
statement with a reference to this .
Here is a method to replace each element in an array with its absolute
value, relying on a synchronized statement to control access to the array:
/** make all elements in the array non-negative */
public static void abs(int[] values) {
synchronized (values) {
for (int i = 0; i < values.length; i++) {
if (values[i] < 0)
values[i] = -values[i];
}
}
}
The values array contains the elements to be modified. We synchronize
values by naming it as the object of the synchronized statement. Now the
loop can proceed, guaranteed that the array is not changed during ex-
ecution by any other code that is similarly synchronized on the values
array. This is an example of what is generally termed client-side syn-
chronizationall the clients using the shared object (in this case the ar-
ray) agree to synchronize on that object before manipulating it. For ob-
jects such as arrays, this is the only way to protect them when they can
be shared directly, since they have no methods that can be synchron-
ized.
The synchronized statement has a number of uses and advantages over a
synchronized method. First, it can define a synchronized region of code
that is smaller than a method. Synchronization affects performancewhile
one thread has a lock another thread can't get itand a general rule of
concurrent programming is to hold locks for as short a period as pos-
sible. Using a synchronized statement, you can choose to hold a lock
 
Search WWH ::




Custom Search