替代CopyOnWriteArrayList用于频繁写入,偶尔迭代 [英] alternative to CopyOnWriteArrayList for frequent writes, occasional iterating

查看:748
本文介绍了替代CopyOnWriteArrayList用于频繁写入,偶尔迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList 是被无限地缓存和跨多个线程共享。

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.

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

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

我目前正在为线程安全做准备。首先, CopyOnWriteArrayList 似乎是最好的答案,但它的性能关注我,因为修改会比其他任何事情更频繁。

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.

推荐答案

您可以尝试使用 .setFromMap(new ConcurrentHashMap< T,Boolean>()); 这将给你一个并发的哈希集,它将给你附近O(1)添加和删除。

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.

这篇关于替代CopyOnWriteArrayList用于频繁写入,偶尔迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆