Java Reference
In-Depth Information
These methods seem harmless, and in a sense they are—they can't corrupt the Vector , no
matter how many threads call them simultaneously. But the caller of these methods might
have a different opinion. If thread A calls getLast on a Vector with ten elements, thread
B calls deleteLast on the same Vector , and the operations are interleaved as shown in
Figure 5.1 , getLast throws ArrayIndexOutOfBoundsException . Between the call
to size and the subsequent call to get in getLast , the Vector shrank and the index
computed in the first step is no longer valid. This is perfectly consistent with the specification
of Vector —it throws an exception if asked for a nonexistent element. But this is not what
a caller expects getLast to do, even in the face of concurrent modification, unless perhaps
the Vector was empty to begin with.
Figure 5.1. Interleaving of Getlast and Deletelast that throws
ArrayIndexOut-OfBoundsException .
Because the synchronized collections commit to a synchronization policy that supports
client-side locking, [1] it is possible to create new operations that are atomic with respect to
other collection operations as long as we know which lock to use. The synchronized collec-
tion classes guard each method with the lock on the synchronized collection object itself. By
acquiring the collection lock we can make getLast and deleteLast atomic, ensuring
Search WWH ::




Custom Search