4

is this ENUM code thread safe?

enum One{
    IONE;
    public mone(){
        // some code
    }
}

when above code is not thrad safe?

arjun
  • 57
  • 2
  • 6

3 Answers3

4

An enum value is guaranteed to only be initialized once, ever, by a single thread, before it is used.However, methods that you add to an enum class do not carry any thread safety guarantee. If you have an enum so that the methods don't change its state, then they are by definition thread safe

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

It is, as long as your method itself is.

Enums are treated specially:

  • they are initialized when the class is loaded (which is why you can use them in annotations);
  • they are always final;
  • enum values are always static final.
fge
  • 119,121
  • 33
  • 254
  • 329
0

There are no shared data in the One enum, and all the variables in mone (which needs a return type) are local ones. So, it all depends on the content of mone. If the method uses singletons with state in other classes, you can have problems.

Eric Jablow
  • 7,874
  • 2
  • 22
  • 29
  • can you explain more about this with code ---'If the method uses singletons with state in other classes, you can have problems.' – arjun Aug 27 '13 at 17:31
  • Sorry--I made too many typos. One use of enums, popularized by Joshua Bloch in "Effective Java", is to turn them into the only member of an enum. Then, it's impossible to construct two of the same 'singleton' class. However, I've seen people give those singleton enums mutable data, or to call methods on objects with mutable data. Without explicit synchronization, two threads accessing the enum can interfere with each other. So, if you want a singleton as an enum, don't make the data mutable. – Eric Jablow Aug 27 '13 at 20:48
  • It seems like the problem you described actually have nothing to do with the Enum-implemented Singleton itself. This concurrency issue could affect all kinds of Singleton as long as its implementation doesn't handle the multi-threading stage properly. It is actually the Java concurrency issue. – hackjutsu Jan 15 '16 at 18:40