拍摄集合的快照

编程入门 行业动态 更新时间:2024-10-21 11:31:07
本文介绍了拍摄集合的快照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我设置了项目,并且想要发送它进行并行处理。

但是,我想修改原始设置后,它会导致一些并发问题,所以我认为拍摄快照或某些集合并发送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);

更多推荐

拍摄集合的快照

本文发布于:2023-10-07 15:11:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快照

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!