The most efficient but thread safe list / set

There are many different collections in Java designed for concurrency and thread safety, and I am at a loss as to which one to choose for my situation.

Several threads can call .add() and .remove() , and I will copy this list often with something like List<T> newList = new ArrayList<T>(concurrentList) . I will never iterate over a parallel list.

I thought of something like CopyOnWriteArrayList , but I read that it can be very inefficient because it copies itself every time it changes. I hope to find a good compromise between safety and efficiency.

What is the best list (or set) for this situation?

+6
source share
4 answers

As @SpiderPig said, the best scenario with List would be an immutable, single-linked list.

However, looking at what is being done here, List not required (comment by @bhspencer). A ConcurrentSkipListSet will work most efficiently (@augray).

This answer dedicated to the topic gives more information about the pros and cons of various parallel collections.

+3
source

You might want to find out if ctrie is suitable for your use case - it has thread-safe add and remove operations and a “copy” (in fact, snapshot) data structure works in O (1). I know two implementations of the JVM data structure: one implementation , two implementations .

+1
source
 Collections.newSetFromMap(new ConcurrentHashMap<...>()) 

As a rule, a normal set is executed (HashSet is a truly modified shell on top of the HashMap). It offers both performance advantages / concurrecy from ConcurrentHashMap, and it does not have additional features such as ConcurrentSkipListSet (orders), COW lists (copying each modification) or parallel queues (FIFO / LIFO ordering).

Edit: I did not see @bhspencer's comment on the original post, apologizing for the theft of the spotlight.

0
source

Hash hash hash will be better than List. Add the latter and delete first will be fine with LinkedList. Search will be fast in arraylist based on array index.

Thanks,

0
source

Source: https://habr.com/ru/post/988684/


All Articles