views:

461

answers:

2

Hi,

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

+2  A: 

This technique is absolutely thread-safe. An enum value is guaranteed to only be initialized once, ever, by a single thread, before it is used. However, I'm not sure whether it is when the enum class is loaded or the first time the enum value itself is accessed. Using this technique is actually a bit safer than other techniques, because there is not even a way with reflection to get a second copy of your enum-based singleton.

Mike Daniels
If the enum does something really stupid in its static intialiser (or elsewhere), it could theoretically be a problem. (Static initialisation is a different phase from class loading - see 3-argument `Class.forName`.)
Tom Hawtin - tackline
yes i tried to find a reflective way to init another enum, and i couldn't.
portoalet
@Mike How can I find out when the enum value is initialized, ie when the enum class is loaded or the first time the enum value is accessed?
portoalet
@portoalet, as you know, each enum value is like its own instance of an object and can have constructors and methods. I would do a little test to see when an enum value's constructor gets called. You could create a small test scenario with an enum with two values, and only try to use one of them, and see if only one enum value's constructor gets called or both of them do.
Mike Daniels
+3  A: 

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.

Itay