java中的枚举如何线程安全? [英] How thread-safe is enum in java?

查看:324
本文介绍了java中的枚举如何线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java中的枚举如何线程安全?
我正在使用枚举(根据Bloch的有效Java)实现一个Singleton,
我应该担心我的单例枚举的线程安全?
有没有办法证明或反驳它是线程安全的?

  // Enum singleton  - 首选方法
public enum Elvis {
INSTANCE;
public void leaveTheBuilding(){...}
}

谢谢

解决方案

正如@Mike所说,枚举的创建保证线程安全。但是,添加到枚举类的方法不会承担任何线程安全保证。特别地,方法 leaveTheBuilding 可以由多个线程同时执行。如果这种方法有副作用(改变一些变量的状态),那么你需要考虑保护它(即使它 synchronized )或其部分。


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? Is there a way to prove or disprove that it is thread safe?

// Enum singleton - the preferred approach
public enum Elvis { 
    INSTANCE;
    public void leaveTheBuilding() { ... }
}

Thanks

解决方案

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.

这篇关于java中的枚举如何线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆