开发者

Converting Hibernate's PersistentSet into CopyOnWriteArraySet

开发者 https://www.devze.com 2023-03-11 02:13 出处:网络
I am using CopyOnWriteArraySet in the following class because I simply like its thread-safe iterator.

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消