Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 522
user1812379 Avatar asked Nov 17 '25 10:11

user1812379


1 Answers

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").

like image 75
cic Avatar answered Nov 18 '25 23:11

cic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!