拍摄集合的快照 [英] Take a snapshot of a Set

查看:106
本文介绍了拍摄集合的快照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

这篇关于拍摄集合的快照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆