简体   繁体   English

Java中的线程安全Enumset

[英]Thread-safe Enumset in Java

I use the following code to initialize a synchronized instance of an EnumSet: 我使用以下代码初始化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? 在这种情况下,我是否保留了EnumSet的所有好处,如紧凑性和效率?
  • is there a more... let'say... semantically rich way to get an empty and synchronized instance of EnumSet? 是否有更多... ... ...语义丰富的方式来获得一个空的和同步的EnumSet实例?

Well from the javadoc : 好吧,来自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. 如果不存在此类对象,则应使用Collections.synchronizedSet(java.util.Set)方法“包装”该集合。 This is best done at creation time, to prevent accidental unsynchronized access: 这最好在创建时完成,以防止意外的不同步访问:

Set s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class)); 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. 我也会像你一样保持Set final It's odd that they don't mention it in the javadoc. 奇怪的是他们没有在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. 编辑 :回答第一个问题,简短回答是,答案很长,是的,但你必须支付同步的价格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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