3

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?
jilt3d
  • 3,864
  • 8
  • 34
  • 41
  • Looks fine to me. Collections.synchronizedSet is just a wrapper and doesn't change EnumSet or replace it. – Peter Lawrey Jun 23 '14 at 16:28
  • I just checked the source code - indeed it is only a wrapper which adds mutex-based synchronization. And it seems that there is no any (more readable) one-liner provided by any library. – jilt3d Jun 25 '14 at 10:23

1 Answers1

8

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.

Community
  • 1
  • 1
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
  • Thanks, I checked javadoc of both `EnumSet` and `Collections` but didn't find the answers. However, checking the source code gave the answer of the first question. Regarding, the second one - I was hoping for Guava to provide such a method but it seems there is not. – jilt3d Jun 25 '14 at 10:30