Java Reference
In-Depth Information
Thread B then increments max at and returns. Later, Thread A gets to run again; it re-
sumes at and increments max past the last valid object. So not only have we lost an ob-
ject, but we have an uninitialized reference in the array. This state of affairs is shown in
Figure 22-2 .
Figure 22-2. Nonthreadsafe add method in operation: normal and failed updates
Now you might think, “No problem, I'll just combine the two lines of code!”:
data[max++] = obj;
As the game show host sometimes says, “Bzzzzt! Thanks for playing!” This change makes
the code a bit shorter but has absolutely no effect on reliability. Interrupts don't happen con-
veniently on Java statement boundaries; they can happen between any of the many JVM ma-
chine instructions that correspond to your program. The code can still be interrupted after the
store and before the increment. The only good solution is to use proper synchronization.
Making the method synchronized means that any invocations of it will wait if one thread
has already started running the method:
public synchronized void add(Object obj) {
...
}
 
 
 
Search WWH ::




Custom Search