Reputation: 14238
I know that ArrayList
is not synchronized, but I can access it in a synchronized way as :
synchronized( arraylist )
{
arraylist.add( "new item" );
}
or I can use a vector
instead - which I see from every blog that it should be avoided.
Please let me know your thoughts
Upvotes: 1
Views: 1669
Reputation: 19221
Yes, you can access a List
and make it synchronized
by using blocks as you have described. Note that you must also synchronize when reading from the list in order to be totally safe.
An alternative (and IMO better) approach is to use one of the following:
Alternative 1: Collections.synchronizedList:
List<SomeType> sList = Collections.synchronizedList(arrayList);
sList.add(...); // synchronized, no synchronized-block needed
The returned list will be synchronized for updates but iterations must still be in a synchronized
block:
// Iterating...
synchronized (sList) {
for (SomeType s : sList) {
// do stuff
}
}
You can find the JavaDocs here
Alternative 2: CopyOnWriteArrayList:
You can find the JavaDocs here
A thread-safe variant of
ArrayList
in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.
The second alternative is obviously more memory-consuming if you perform a lot of writes.
Upvotes: 1
Reputation: 85779
There is a concurrent List
implementation: CopyOnWriteArrayList
that supports concurrency and is better than the options described above.
Still, I would recommend using another collection like a concurrent Queue
through BlockingQueue
and implemented by LinkedBlockingQueue
. I would ask you to provide more info on your problem to get more accurate help.
Upvotes: 2