1

There are two ways to use a CopyOnWriteArraySet:

// A
Set<Object> set = new CopyOnWriteArraySet<>();

and

// B
CopyOnWriteArraySet<Object> set = new CopyOnWriteArraySet<>();

With 'normal' sets like HashSet and TreeSet, case A is preferred, because it allows easy switching of the Set implementation.

However, in this case a conscious choice is made for a specific thread-safe Set implementation. Should I use case B to signify this intent?

2 Answers 2

2

You can deliberately declare a more specific type to document your threading policy. However, a functioning threading policy requires much more than judiciously chosen types, so it doesn't add that much value.

In your example, you are invoking the constructor of the concrete class in the very same line, so the choice would have been obvious even anyway. It would be more worthwhile to use types for communicating if your set were returned to an external user, e.g. via an interface or a method return type.

2

It all depends to whom you want to signal this intent.

Specifics of your implementation should not be leaked to your clients. As @Killian mentions, if this fact is significant for clients useing your functionality you can document your intent into an interface that hides your actual implementation.

If you want to signal this to people that can actually modify the code, again, this can be easily documented at the method, interface level that hides the implementation.

I would suggest to stick to the first case for flexibility (as you may switch to another similar implementation) and clearly state the intentions in your documentation. Of course, having the right Unit Tests in place will prevent people adding "wrong" sets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.