Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)      list.remove(item); } 

Thanks!

like image 326
shadowfax Avatar asked Jul 06 '12 10:07

shadowfax


People also ask

What is a synchronized list in Java?

The synchronizedList() method of java. util. Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.

How can you synchronize an ArrayList in Java?

In order to get a synchronized list from an ArrayList, we use the synchronizedList(List <T>) method in Java. The Collections. synchronizedList(List <T>) method accepts the ArrayList as an argument and returns a thread safe list.

Is ArrayList class synchronized in Java?

Implementation of ArrayList is not synchronized by default. It means if a thread modifies it structurally and multiple threads access it concurrently, it must be synchronized externally.


1 Answers

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:

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())         foo(i.next()); } 

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

like image 126
Peter Lawrey Avatar answered Oct 04 '22 16:10

Peter Lawrey