Enum singleton implementation

J. Bloch, in its efficient Java, suggests that we use a singleton enum-based implementation. For instance:

public enum Application { INSTANCE; //methods, fields } 

This implementation is good for serialization, because enumerations provide us with the ability to serialize by default (and we don’t need to be afraid to get two different instances when deserializing an object).

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

+5
source share
2 answers

The actual behavior of enum when installing an instance does not have a thread safety issue . However, you need to make sure that the state of the instance itself is thread safe.

Interacting with Application fields and methods is a risk - using either careful synchronization and locking, or purely parallel data, and carefully checking that other inconsistencies cannot happen, will be your best choice here.

+8
source

Singleton ensures that you have only one class instance for each class loader.

You only need to take care of concurrency if your singleton has mutable state. I mean, if singleton data stores some volatile data.

In this case, you should use some kind of synchronization blocking mechanism to prevent simultaneous state modification and / or use thread-safe data structures.

+1
source

All Articles