Java Reference
In-Depth Information
Even though the iteration in
Listing 5.3
can throw an exception, this doesn't mean
Vector
isn't thread-safe. The state of the
Vector
is still valid and the exception is in fact in con-
formance with its specification. However, that something as mundane as fetching the last ele-
ment or iteration throw an exception is clearly undesirable.
The problem of unreliable iteration can again be addressed by client-side locking, at some
additional cost to scalability. By holding the
Vector
lock for the duration of iteration, as
iterating it. Unfortunately, we also prevent other threads from accessing it at all during this
time, impairing concurrency.
Listing 5.4. Iteration with Client-side Locking.