我设置了项目,并且想要发送它进行并行处理。
但是,我想修改原始设置后,它会导致一些并发问题,所以我认为拍摄快照或某些集合并发送THAt进行处理是很好的。
将 clone 工作好吗? 或者我应该自己创建一个新的 Set 吗? 或者有一些不错的方式我缺少?
我现在使用这个,它似乎工作很不错:
public class BufferedHashSet< E>扩展HashSet< E> { 私人名单< E> toAdd = new LinkedList< E>(); private List< Object> toRemove = new LinkedList< Object>(); @Override public boolean add(E e) { synchronized(this){ toAdd.add(e); return true; } } @Override public boolean remove(Object e) { synchronized(this){ toRemove .add(e); return true; } } public void flush() { synchronized(this){ for(E e:toAdd){ super.add(e); } for(Object e:toRemove){ super.remove(e); } toAdd.clear(); toRemove.clear(); } } }解决方案>
在我看来,最优雅的解决方案是使用 Set.addAll()方法。
设置集; 设置snapshot = new TreeSet<>(); //或任何使用的Set实现 snapshot.addAll(set);
I have Set with items, and want to send it for parallel processing.
However, I want to modify the original set afterwards and it'd cause some concurrency issues, so I think it'd be nice to take a snapshot or something of the Set and send THAt for the processing.
Will clone work good? Or should I make a new Set of it myself? Or is there some nice way I'm missing?
Edit: I'm now using this, it seems to work pretty nice:
public class BufferedHashSet<E> extends HashSet<E> { private List<E> toAdd = new LinkedList<E>(); private List<Object> toRemove = new LinkedList<Object>(); @Override public boolean add(E e) { synchronized (this) { toAdd.add(e); return true; } } @Override public boolean remove(Object e) { synchronized (this) { toRemove.add(e); return true; } } public void flush() { synchronized (this) { for (E e : toAdd) { super.add(e); } for (Object e : toRemove) { super.remove(e); } toAdd.clear(); toRemove.clear(); } } }解决方案
In my opinion the most elegant solution is to use Set.addAll() method.
Set set; Set snapshot = new TreeSet<>(); //or any Set implementation you use snapshot.addAll(set);
更多推荐
拍摄集合的快照
发布评论