Re: Numpty "synchronized" question with ArrayList
On 25-10-2010 07:25, Richard Maher wrote:
WRT JavaDocs for the ArrayList class: -
Note that this implementation is not synchronized. If multiple threads
access an ArrayList instance concurrently, and at least one of the threads
modifies the list structurally, it must be synchronized externally. (A
structural modification is any operation that adds or deletes one or more
elements, or explicitly resizes the backing array; merely setting the value
of an element is not a structural modification.) This is typically
accomplished by synchronizing on some object that naturally encapsulates the
list. If no such object exists, the list should be "wrapped" using the
Collections.synchronizedList method. This is best done at creation time, to
prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(...));
and so on. . .
Can someone please explain why locking/synchronizing on the ArrayList
instance itself is not sufficent to serialize access?
eg: -
ArrayList<MyObj> myList = new ArrayList<MyObj>();
synchronized (myList) {
myList.add(aMyObj1);
lotsoffatomicisolatedstuff();
}
Are wrapper classes like collections really necessary here?
The old Vector class has methods that are synchronized.
The new ArrayList class does not.
There are 3 relevant cases:
A) single threaded access to the data
B) multi threaded but single operation access to the data
C) multi threaded and multi operation access to the data
Vector ArrayList
A unnecessary synchronized fine
B fine need external synchronized
C need external synchronized need external synchronized
+unnecessary synchronized
So because A+C is more likely than B then ArrayList is
the right way to do it.
Java found out of that in Java 1.2.
And surprisingly .NET started the same way as Java (even though 1.2
was out) and then changed in 2.0.
To make the handling of B a little bit easier then
the Collections.synchronizedList method exist to save
using synchronized everywhere the methods are called.
This both makes the code more readable and prevents
someone forgetting to use synchronized for access.
So definitely good.
But it is only applicable to case B.
Arne