Singleton singleton single layer with lazy loading ability

I read a lot of forums and posts about different styles for implementing a single-color template in java and it seems that "Enum is the best way to implement a single template in java" !! I wonder how I can use Java Enum to implement a SingleTone template in java with lazy loading . since Enums are just classes. When the class is first used, it is loaded by the JVM, and all its static initialization is performed. enumeration members are static, so they will all be initialized.

Does anyone know how I can use lazyloading-enabled enumeration?

+4
source share
2 answers

The reason you read says that this is the easiest way to make lazy singles, because it should just work. Try the following:

public class LazyEnumTest { public static void main(String[] args) throws InterruptedException { System.out.println("Sleeping for 5 seconds..."); Thread.sleep(5000); System.out.println("Accessing enum..."); LazySingleton lazy = LazySingleton.INSTANCE; System.out.println("Done."); } } enum LazySingleton { INSTANCE; static { System.out.println("Static Initializer"); } } 

Here I get the output in the console:

 $ java LazyEnumTest Sleeping for 5 seconds... Accessing enum... Static Initializer Done. 
+5
source

When the class is first used, it is loaded by the JVM, and all its static initialization is performed. enumeration members are static, so they will all be initialized.

In fact, classloader loads classes (sounds funny) only after the first call to these classes. And only one reason to access the enum-singleton class is to get an instance of it.

This is why the singleton enum type singleletone in Java is called lazy - this value is not initialized until you first access it.

Related questions:

+4
source

All Articles