static
initializer blocks are single threaded using a Lock internal to the JVM. i.e. it doesn't appear in a jstack
trace like other locks. No other thread can access anything the class until it has been initialized. This is true of all classes, not just enum
.
enum
are initialized in a static initializer block generated by the compiler.
Also are the methods declared in enum are thread-safe or any special care has to be taken?
Again, enum
are just like regular classes. Only the methods you mark as synchronized
are synchronized. Note: just adding synchronized doesn't make it thread safe. ;)
While enum
are effectively static final
instances, you can modify their fields ie. the fields on an enum are not final
by default. Also you can modify enums by messing with the internal structure of the class using reflection and Unsafe.allocateInstance. Generally this is not a good idea.
From 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.