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

查看:32
本文介绍了替代 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.

推荐答案

你可以尝试使用 Collections.newSetFromMap(new ConcurrentHashMap()); 这会给你一个并发哈希集将为您提供接近 O(1) 的添加和删除.

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.

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

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