Search code examples
javamultithreadingthread-safetyadditionjava.util.concurrent

Java Multithreading: cheap operation to add object to List/Queue/Set


So basically I need a way to add an object (let's call it Element) to a List/Queue/Set or something similar with multiple threads. Since I need to add a lot of elements (not sure how many but trust me A LOT), the operation should be cheap. Removing them is not necessary. Also it's extermly important that every Element is added to the list.

Basically I'm looking for this:

  • threadsafe
  • cheap add function
  • not comparable/not sorted
  • every element needs to be added

Since CopyOnWriteArrayList sounds quite expensive in my case, I don't think this is an option.

Unfortunately I can't make the Element comparable so ConcurrentSkipListSet is not an option.

Collections.synchronizedList() sounds too expensive as well.

Currently I'm thinking about using a ConcurrentLinkedQueue or just synchronizing the add method like this:

private synchronized void add(Element elem){
    elements.add(elem);
}

Solution

  • In general, you should stick to the methods and classes from the JDK library; they tend to be rather optimized, and will be down the road in future versions which will result in your code being updated without effort in your part. In fact, this is one item in Joshua Bloch's Effective Java.

    Heeding that rule, and since you don't seem to really care about what kind of collection you really get ("List/Queue/Set" in your question), why don't you just do

    Collection<YourData> synced = Collections.synchronizedCollection(new LinkedList<>());
    

    LinkedList optimizes adding elements (as opposed to ArrayList which will copy the underlying array when the capacity is exhausted), and synchronizedCollection will do the synchronized wrapping (if you look into the code, it's implemented exactly as you propose). So does synchronizedList btw.