5

J. Bloch in his Effective Java suggests we use an enum-based singleton implementation. For instance:

public enum Application {

    INSTANCE;

    //methods, fields

}

This implementation is nice in the case of serialization because enums provide us with the capability of serialization by default (and we don't have to be afraid of getting two different instances while deserializing the object).

My question is how this implementation respects multhreading. How to make it thread-safe? What would we probably get if we try to access it from different threads?

Oliphaunt
  • 200
  • 9
St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • You make it thread-safe as you make any other object thread-safe: by making sure access to its state is properly synchronized. If it doesn't have state, it's inherently thread-safe. – JB Nizet Jun 22 '15 at 14:29
  • 2
    The advantage from enum is that it is thread-safe initialized. Another singleton pattern requires an inner class to achieve the same and is more verbose/magic. – Joop Eggen Jun 22 '15 at 14:31

2 Answers2

8

The actual enum behavior of instatiating the instance doesn't have an issue with thread safety. However, you will need to make sure that the instance state itself is thread-safe.

The interactions with the fields and methods of Application are the risk--using either careful synchronization and locking, or purely concurrent data and careful verification that other inconsistencies can't happen, will be your best bet here.

Community
  • 1
  • 1
nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • So I still have to make some methods of the enum synchronized to ensure thread-safety? – St.Antario Jun 22 '15 at 14:35
  • @St.Antario Yes, since wrapping state in an enum isn't a "magic bullet" for thread safety. Treat it as any class that needs to be thread-safe, but don't worry about thread-safety of the constructor (aside from leaking `this`). – nanofarad Jun 22 '15 at 14:36
1

Singleton ensures you only have one instance of a class per class loader.

You only have to take care about concurrency if your singleton has a mutable state. I mean if singleton persist some kind of mutable data.

In this case you should use some kind of synchronization-locking mechanishm to prevent concurrent modification of the state and/or use thread-safe data structures.

Ezequiel
  • 3,477
  • 1
  • 20
  • 28