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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With