Java Reference
In-Depth Information
Synchronizing Threads with the synchronized Keyword
Problem
You need to protect certain data from access by multiple threads.
Solution
Use the synchronized keyword on the method or code you wish to protect.
Discussion
I discussed the synchronized keyword briefly in Handling Multiple Clients . This keyword
specifies that only one thread at a time is allowed to run the given method (or any other syn-
chronized method in the same class) in a given object instance (for static methods, only one
thread is allowed to run the method at a time). You can synchronize methods or smaller
blocks of code. It is easier and safer to synchronize entire methods, but this can be more
costly in terms of blocking threads that could run. You can simply add the synchronized
keyword on the method. For example, many of the methods of Vector (see Like an Array,
but More Dynamic ) are synchronized, to ensure that the vector does not become corrupted or
give incorrect results when two threads update or retrieve from it at the same time.
Bear in mind that threads can be interrupted at almost any time, in which case control is giv-
en to another thread. Consider the case of two threads appending to a data structure at the
same time. Let's suppose we have the same methods as Vector , but we're operating on a
simple array. The add() method simply uses the current number of objects as an array index,
then increments it:
public void add(Object obj) {
data[max] = obj; //
max = max + 1; //
}
Threads A and B both wish to call this method. Suppose that Thread A gets interrupted after
but before , and then Thread B gets to run.
Thread B does , overwriting the contents of data[max] ; we've now lost all reference to
the object that Thread A passed in!
 
 
Search WWH ::




Custom Search