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

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

我目前正在preparations线程安全。起初,<一href=\"http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html\">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.

推荐答案

您可以尝试使用 Col​​lections.setFromMap(新的ConcurrentHashMap&LT; T,布尔&GT;()); 这会给你一个并发的哈希集合,这将给你接近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天全站免登陆