简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM