Pau*_*ora 14 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...
}
Run Code Online (Sandbox Code Playgroud)
我正在为线程安全做准备.起初,CopyOnWriteArrayList似乎是最好的答案,但它的性能令我担忧,因为修改将比其他任何事情更频繁.
手动更改为包装类是否会更好?
public Iterator<T> iterator() {
return new ArrayList<T>(innerList).listIterator();
}
//plus concurrency tweaks for any non-atomic modifications to innerList
Run Code Online (Sandbox Code Playgroud)
请帮我找到最好的方法.
您可以尝试使用a.Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());这将为您提供一个并发哈希集,它将为您提供近O(1)添加和删除.
如果可以使用Queue接口而不是List,则可以使用ConcurrentLinkedQueue。我认为,使用Queue可以满足您比预期更多的用例。List的一个主要优点是随机访问(基于索引),但是在并发情况下,随机访问既不是必需的也不是所希望的。
ConcurrentLinkedQueue是Queue的出色并发实现。
| 归档时间: |
|
| 查看次数: |
2044 次 |
| 最近记录: |