Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe Enumset in Java

I use the following code to initialize a synchronized instance of an EnumSet:

private final Set<MyClass> instance = Collections.synchronizedSet(EnumSet.noneOf(MyClass.class));

I have two questions:

  • do I retain all the benefits of an EnumSet like compactness and efficiency in this case?
  • is there a more... let'say... semantically rich way to get an empty and synchronized instance of EnumSet?
like image 934
jilt3d Avatar asked Jan 20 '26 17:01

jilt3d


1 Answers

Well from the javadoc:

If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the enum set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet(java.util.Set) method. This is best done at creation time, to prevent accidental unsynchronized access:

Set s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class));

so I think that's the best you can do.

I would also keep the Set final as you did. It's odd that they don't mention it in the javadoc.

EDIT: to answer the first question, short answer yes, long answer, yes but you have to pay the price for synchronization on top of that.

like image 122
Giovanni Botta Avatar answered Jan 22 '26 13:01

Giovanni Botta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!