Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

single-element enum type singletone with lazy loading capability

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?

like image 293
Morteza Adi Avatar asked Mar 18 '13 05:03

Morteza Adi


People also ask

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.

What is enum Singleton?

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.

Why is enum thread safe?

An enum value is guaranteed to only be initialized once, ever, by a single thread, before it is used.


1 Answers

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.
like image 95
DaoWen Avatar answered Oct 13 '22 02:10

DaoWen