I read many forums and posts about different style to implement single-tone pattern in java and seems "Enum are the best way to implement singletone pattern in java"!! I wonder how can i use Java Enum to implement SingleTone pattern in java with lazy-loading capability. since Enums are just classes. The first time a class is used, it gets loaded by the JVM and all of its static initialization is done. the enum members are static , so they're all going to be initialized.
does anyone know how can i use enum with lazyloading support?
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.
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards.
An enum value is guaranteed to only be initialized once, ever, by a single thread, before it is used.
The reason the source you read said it's the easiest way to do lazy singletons is because it should just work. Try this:
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's the output I get in the console:
$ java LazyEnumTest
Sleeping for 5 seconds...
Accessing enum...
Static Initializer
Done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With