Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Efficient but Thread-Safe List/Set

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?

like image 399
Rogue Avatar asked Jun 08 '15 02:06

Rogue


People also ask

Which set is thread-safe?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

Is HashSet thread-safe?

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 .

Is ArrayList thread-safe?

Any method that touches the Vector 's contents is thread safe. ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe.

Is list AddRange 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.

Is set collection thread-safe?

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.


1 Answers

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.

like image 90
Rogue Avatar answered Oct 14 '22 05:10

Rogue