Java has tons of different Collections designed for concurrency and thread safety, and I'm at a loss as to which one to choose for my situation.
Multiple threads may be calling .add()
and .remove()
, and I will be copying this list frequently with something like List<T> newList = new ArrayList<T>(concurrentList)
. I will never be looping over the concurrent list.
I thought about something like CopyOnWriteArrayList
, but I've read that it can be very inefficient because it copies itself every time it's modified. I'm hoping to find a good compromise between safety and efficiency.
What is the best list (or set) for this situation?
The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
Most of the collections such as ArrayList, LinkedList, HashSet, HashMap, etc., are not thread-safe. If two parallel threads modify any of these collections parallelly, the user can get stale data or ConcurrentModificationException .
Any method that touches the Vector 's contents is thread safe. ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe.
No it is not thread-safe. Thread A could call AddRange on your list. It could iterate partially over the collection and switch threads. Thread B could call Add/Remove, etc.
This method accepts an object of Set interface and, returns a synchronized (thread-safe) set backed by the specified set. This method accepts an object of the Map interface and, returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
As @SpiderPig said, the best case scenario with a List
would be an immutable, singly-linked list.
However, looking at what's being done here, a List
is unnecessary (@bhspencer's comment). A ConcurrentSkipListSet
will work most efficiently (@augray).
This Related Thread's accepted answer offers more insight on the pros and cons of different concurrent collections.
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