I am using CopyOnWriteArraySet in the following class because I simply like its thread-safe iterator.
public class MyClass{
Set _children = new CopyOnWriteArraySet();
public void setChildren(Set children){
_children = children;
}
public Set getChildren(){
return _children;
}
}
However, I also use Hibernate for persistency which replaces my CopyOnWriteArraySet with its own PersistentSet (which uses HashSet internally).
Unfortunately, HashSet is not thread-safe, so I want my CopyOnWrit开发者_开发问答eArraySet back.
What's best practice here for the conversion?
My personal, naive attempt would be to replace the setter with this:
public void setChildren(Set children){
CopyOnWriteArraySet newSet = null;
if ((children instanceof CopyOnWriteArraySet) == false){
newSet = new CopyOnWriteArraySet(children);
}
else{
newSet = (CopyOnWriteArraySet)children;
}
_children = newSet;
}
Is that a good way of working around this issue?
精彩评论