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)
list.remove(item);
}
Thanks!
Yes, Just be careful if you are also iterating over the list, because in this case you will need to synchronize on it. From the Javadoc:
Or, you can use
CopyOnWriteArrayListwhich is slower for writes but doesn’t have this issue.