shadowfax shadowfax - 1 year ago 161
Java Question

Java Synchronized list

I have a pre-populated array list. And I have multiple threads which will remove elements from the array list. Each thread calls the remove method below and removes one item from the list. Does the following code give me consistent behavior ?

ArrayList<String> list = Collections.synchronizedList(new ArrayList<String>());

void remove(String item)
do something; (doesn't work on the list)


Answer Source

Yes, Just be careful if you are also iterating over the list, because in this case you will need to synchronize on it:

It is imperative that the user manually synchronize on the returned list when iterating over it:

List list = Collections.synchronizedList(new ArrayList());
synchronized (list) {
    Iterator i = list.iterator(); // Must be in synchronized block
    while (i.hasNext())

Or, you can use CopyOnWriteArrayList which is slower for writes but doesn't have this issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download