Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing enum-based singleton

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?

like image 283
St.Antario Avatar asked Jun 22 '15 14:06

St.Antario


People also ask

How would you implement singleton using enum?

Singleton using Enum in Java: By default creation of the Enum instance is thread-safe, but any other Enum method is the programmer's responsibility. You can access it by EasySingleton. INSTANCE, far simpler than calling getInstance() function on Singleton.

Why enum is best for singleton?

Since enums are inherently serializable we don't need to implement it with serializable interface. Reflection problem is also not there. Therefore, it is 100% guaranteed that only one instance of the singleton is present within a JVM. Thus, this method is recommended as the best method of making singletons in java.

What is the best way to implement a singleton class?

The most popular approach is to implement a Singleton by creating a regular class and making sure it has: A private constructor. A static field containing its only instance. A static factory method for obtaining the instance.

Is enum singleton lazy?

In your case, the singleton will be initialised when the enum class is loaded, i.e. the first time enumClazz is referenced in your code. So it is effectively lazy, unless of course you have a statement somewhere else in your code that uses the enum.


2 Answers

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.

like image 98
nanofarad Avatar answered Sep 24 '22 02:09

nanofarad


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.

like image 41
Ezequiel Avatar answered Sep 24 '22 02:09

Ezequiel