June 21, 2011

Is it possible to synchronized ArrayList?

ArrayList is not synchronized. But there's a way the get a synchronized
one as mentioned in java.util.ArrayList's JavaDoc:

List list = Collections.synchronizedList(new ArrayList(...));

In java.util.Collections' JavaDoc you can read that "It is imperative
that the user manually synchronize on the returned list when iterating
over it:"

synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}

Using a synchronized ArrayList results in additional work, why not use a
java.util.Vector instead? Is there an advantage in using this approach?


I'm not sure which extra work you're talking about. Do you mean the fact
that you have to call Collections.synchronizedList() with ArrayList, or do
you mean the above example of synchronizing on iteration? For the latter,
the same would hold true for Vector. If you want to iterate over a Vector
which may be being modified from other threads, you would need to put the
whole iteration in a synchronized block, just as you would need to for
ArrayList. Vector just has synchronized methods, but it can't automatically
synchronize across multiple method calls any more than a synchronized
ArrayList can.

As for using
Collections.synchronizedList(new ArrayList())
vs.
new Vector()
It's really just because the Collections hierarchy is a newer addition to
Java than Vector, and is meant to replace Vector. Vector is just kept
around because there was too much code already using it by the time
Collections were added to the standard library. One of the design decisions
made with the new Collections classes was to make them not be synchronized
by default, and instead provide a way to optionally make them be
synchronized.

I believe the reason for this is that most of the time, method-level
synchronization isn't needed for Collections (or Vectors). Either the
Collection is only accessed from one thread, or any code that's accessing or
modifying it will be contained in some other synchronized method or block as
part of some larger synchronized operation. So making Collections default
to having synchronized methods would just provide a false sense of security
to some programmers, while providing new opportunities for deadlocks.

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts