替代CopyOnWriteArrayList用于频繁写入,偶尔迭代 [英] alternative to CopyOnWriteArrayList for frequent writes, occasional iterating
问题描述
我有一个 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屋!