Take a snapshot of a Set

2019-09-07 04:33发布

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条回答
放荡不羁爱自由
2楼-- · 2019-09-07 05:23

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);
查看更多
登录 后发表回答