Take a snapshot of a Set

二次信任 提交于 2019-12-13 02:54:09

问题


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();
        }
    }
}

回答1:


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);


来源:https://stackoverflow.com/questions/22844619/take-a-snapshot-of-a-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!