Paul Bellora Paul Bellora - 2 months ago 14
Java Question

alternative to CopyOnWriteArrayList for frequent writes, occasional iterating

I have an

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

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) {
//app-specific logic

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

I'm currently making preparations for thread safety. At first,
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.


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