Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to CopyOnWriteArrayList for frequent writes, occasional iterating

I have an ArrayList that is to be cached and shared across multiple threads indefinitely. Operations include frequent adds and removes, plus occasional iterating over it.

The ArrayList lives in a wrapper class which manages access to it:

public class MyListWrapper<T> implements Iterable<T> {

    private List<T> innerList = new ArrayList<T>();

    public Iterator<T> iterator() {
        return innerList.listIterator();
    }

    public void add(T element) {
        innerList.add(element);
        //app-specific logic
    }

    //remove(T), etc in the same pattern...
}

I'm currently making preparations for thread safety. At first, CopyOnWriteArrayList seemed like the best answer, but its performance concerns me, since modifications will be made more often than anything else.

Would a manual change to the wrapper class such as this be a better alternative?:

public Iterator<T> iterator() {
    return new ArrayList<T>(innerList).listIterator();
}

//plus concurrency tweaks for any non-atomic modifications to innerList

Please help me find the best approach.

like image 429
Paul Bellora Avatar asked May 20 '11 15:05

Paul Bellora


People also ask

Is CopyOnWriteArrayList concurrent?

CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java.

Why do we use CopyOnWriteArrayList?

CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array. CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare.

What is CopyOnWriteArrayList how it is different from ArrayList in Java?

CopyOnWriteArrayList is thread safe. ArrayList iterator is fail-fast and ArrayList throws ConcurrentModificationException if concurrent modification happens during iteration. CopyOnWriteArrayList is fail-safe and it will never throw ConcurrentModificationException during iteration.


2 Answers

You could try using a Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>()); This will give you a concurrent hash set which will give you near O(1) add and remove.

like image 94
Peter Lawrey Avatar answered Oct 20 '22 02:10

Peter Lawrey


A possibility is to use ConcurrentLinkedQueue if you can live with the Queue interface instead of the List. I would argue that more use cases than you expect may be satisfied with a Queue. One key advantage of List is random access (based on index), but in a concurrent situation random access is neither necessary nor desirable.

ConcurrentLinkedQueue is an excellent concurrent implementation of Queue.

like image 5
sjlee Avatar answered Oct 20 '22 03:10

sjlee