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.