0

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 CopyOnWriteArraySet 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?

Timo Ernst
  • 15,243
  • 23
  • 104
  • 165
  • 1
    You seem to like the `if ((boolean condition) == false)` anti-idiom. What's wrong with `if (!boolean condition)`? – Matt Ball Jun 08 '11 at 14:55
  • 1
    @Matt Ball I sometimes tend to miss the "!" character when debugging code because it's so inconspicuous. So I prefer to use the ==false syntax. – Timo Ernst Jun 08 '11 at 15:04

0 Answers0