Hi there, I'm the Enum singleton

Enum Singletons are probably the most secure way to implement this pattern in Java and are also much easier to write.

By default, enums are themselves singletons and thread safe in Java, so this is already a plus, but we have another plus…Enum Singletons can be Serialized if needed without any further complications.
The downside is that they are always instantiated at classload time, so they are eager initialized.

Depending on the needs, the enum singleton can be a valid option.

Implementing a enum singleton is straightforward

1
2
3
4
5
6
7
8
9
10
11
12
13
package Singleton.enumsingleton;

public enum EnumEagerSingleton {

INSTANCE;

public static String doSomeWork() {

System.out.println("EnumLazySingleton is Doing SomeWork");

return "EnumLazySingleton has finished Doing Work";
}
}

what is going on in this class ?

The above code is very straightforward. Please just note that in the doSomeWork() method we return a String just for the sake of the tests.

An example for the code in this article can be found in git-hub

Share