Java Reference
In-Depth Information
Synchronization
There are two natural divisions when you talk about synchronization: object synchronization
and client synchronization. This section explains the differences between the two.
Internally Synchronized Classes
A
Vector
is a synchronized object and an
ArrayList
is not. What does this mean? It means all
the methods that can access a
Vector
's internal data are synchronized. Any changes made to
a
Vector
object by one thread are guaranteed to be immediately visible to any other thread,
while changes made to an
ArrayList
are not so guaranteed. It does not mean that you are
using the
Vector
object in a thread-safe way in your code. If you wanted that guaranteed, you
would have to synchronize on the
Vector
object directly, just as you would have to synchro-
nize directly on the
ArrayList
.
Note
Vector
is an example of a thread-safe collection; however, it is rare that the thread safety offered
by
Vector
s is required (see the next paragraph for information on what thread safety is guaranteed). If you
do need this kind of thread safety, you may be better off using
Collections.synchronizedCollection
or
similar methods to create a thread-safe collection with the characteristics of your preferred base collection.
■
A synchronized object only promises this: A method called on that object will behave
atomically. For example, imagine that you are running two threads and that
myVector
and
myArrayList
are class member variables.
Thread1
has started to run line 1, and
Thread2
has
yet to start line A.
Thread1:
1 myVector.add("Hello");
2 myArrayList.add("Hello");
Thread2:
A myVector.add("Cruel");
B myArrayList.add("Cruel");
Now, say that in the middle of line 1,
Thread1
slices out.
Thread2
will be unable to slice in
because
Vector
s are synchronized,. You are therefore guaranteed that
Thread2
line A will add
"Cruel"
after
"Hello"
for
myVector
.
This guarantee does not exist for
myArrayList
. That is, if
Thread1
sliced out in the middle
of line 2 and
Thread2
sliced in, the order of adding the items to the
ArrayList
is indeterminate.
Even worse, if one of the adds causes a resize of the internal array, all sorts of strange things
can happen. We might see a
NullPointerException
or
ArrayIndexOutOfBoundsException
, or
one of the adds might be “lost.” All sorts of unpredictable nastiness can emerge from unsyn-
chronized access by multiple threads.