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:
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.