gpt4 book ai didi

java - Java 中的线程安全枚举集

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:10:12 24 4
gpt4 key购买 nike

我使用以下代码来初始化 EnumSet 的同步实例:

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

我有两个问题:

  • 在这种情况下,我是否保留了 EnumSet 的所有优点,例如紧凑性和效率?
  • 是否有更多……比方说……语义丰富的方法来获取 EnumSet 的空同步实例?

最佳答案

嗯从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));

所以我认为这是你能做的最好的。

我也会像您一样保留 Set final。奇怪的是他们没有在 javadoc 中提及它。

编辑:回答第一个问题,简答是,长答是,但你必须为此付出同步的代价。

关于java - Java 中的线程安全枚举集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24370792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com