How thread-safe is enum in java?

后端 未结 4 1909
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 08:01

How thread-safe is enum in java? I am implementing a Singleton using enum (as per Bloch\'s Effective Java), should I worry at all about thread safety for my singleton enum?

4条回答
  •  误落风尘
    2020-11-29 08:41

    As @Mike is saying, creation of enum is guaranteed to be thread safe. However, methods that you add to an enum class do not carry any thread safety guarantee. In particular, the method leaveTheBuilding may be executed, concurrently, by multiple threads. If this method has side effects (changes the state of some variable) then you need to think about protecting it (i.e., make it synchronized) or parts thereof.

提交回复
热议问题