CopyOnWriteArrayList的替代方案,用于频繁写入,偶尔迭代

时间:2011-05-20 15:25:21

标签: java concurrency arraylist

我有一个ArrayList,可以无限期地在多个线程中进行缓存和共享。操作包括频繁的添加和删除,以及偶尔迭代它。

ArrayList位于一个包装类中,用于管理对它的访问:

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...
}

我正在为线程安全做准备。起初,CopyOnWriteArrayList似乎是最好的答案,但它的性能令我担忧,因为修改将比其他任何事情更频繁。

手动更改包装类是否会更好?

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

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

请帮我找到最好的方法。

2 个答案:

答案 0 :(得分:8)

您可以尝试使用Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());这将为您提供并发哈希集,这将使您接近O(1)添加和删除。

答案 1 :(得分:5)

如果您可以使用Queue接口而不是List,则可以使用ConcurrentLinkedQueue。我认为,比你预期的更多用例可能会对队列感到满意。 List的一个关键优势是随机访问(基于索引),但在并发情况下,随机访问既不必要也不可取。

ConcurrentLinkedQueue是Qu​​eue的优秀并发实现。

相关问题