根据 Josh Bloch 的 Effective Java枚举是实现单例模式的最佳方式。
Java 枚举自己负责序列化和线程安全。但是我不明白怎么办。
有人可以解释一下吗?
第二个链接提供了大量关于能够序列化的枚举的详细信息,但我没有得到关于线程安全的充分解释。
另外,在枚举中声明的方法是线程安全的还是需要特别注意?
最佳答案
static
初始化程序 block 是使用 JVM 内部锁的单线程。即它不会像其他锁一样出现在 jstack
跟踪中。在初始化之前,没有其他线程可以访问该类的任何内容。所有类都是如此,而不仅仅是 enum
。
enum
在编译器生成的静态初始化 block 中初始化。
Also are the methods declared in enum are thread-safe or any special care has to be taken?
同样,enum
就像常规类一样。只有标记为 synchronized
的方法才会同步。注意:仅仅添加 synchronized 并不能使其成为线程安全的。 ;)
虽然 enum
是有效的 static final
实例,但您可以修改它们的字段,即。默认情况下,枚举上的字段不是 final
。您还可以通过使用反射和 Unsafe.allocateInstance 扰乱类的内部结构来修改枚举。通常这不是一个好主意。
来自 JLS 8.9.2
for each declared enum constant with the name n, the enum type has an implicitly declared public static final field named n of type E. These fields are considered to be declared in the same order as the corresponding enum constants, before any static fields explicitly declared in the enum type.
关于java - JVM如何保证使用枚举实现的单例线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21748389/