简体   繁体   中英

Which concurrent collection to use?

I have a scenario where an unknown amount of threads add elements to a collection on a server. The data in this collection doesn't have to be sorted and it also won't be iterated. Only two simple operations shall work on this collection:

  1. Adding an element (and removing old element in some cases)
  2. Reading all elements from the collection (not one by one, but the whole collection in order to serialize it and send it to a client. Of course the elements could also be moved to another collection which is then serialized afterwards.)

Which collection would be ideal for this use case? I would choose ConcurrentHashMap, bu I don't know if this choice is good.

Edit: I've forgotten one important requirement: If an element of a certain kind is already in this collection and another one of the same kind is added, then the old one shall be removed before the new one is added. For this requirement I wanted to use hash values to avoid searching. The objects that are stored are simple: They contain a unique user name and some strings and ints. The object's user name should be used as key.

Yes, ConcurrentHashMap is appropriate for this. Use the user name as key type ( K ) and the associated user information ("some strings and ints") as value type ( V ) in the map. Use put to add new key-value pairs, remove to remove key-value pairs, and entrySet to get all key-value pairs in the container (if that is what you meant by "reading all elements from the collection").

I believe there is a concurrent list implementation in java.util.concurrent. CopyOnWriteArrayList which can be useful for your requirement.

or you can use :

 List<Object> objList = Collections.synchronizedList(new ArrayList<Object>());

It's not part of the standard library, but you can use this concurrent doubly linked list . Its iterator is weakly consistent and won't throw a ConcurrentModificationException , or you can use toArray and loop through the returned array.

i think the best thing to use is actually ConcurrentSkipListSet . the reason:

Iterators are weakly consistent, returning elements reflecting the state of the set at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations. Ascending ordered views and their iterators are faster than descending ones.

this means you can go over the entire list and read all of the items, while adding other items. it's completely concurrent !

do note that adding items take O(logN) time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM