9

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?

Morteza Adi
  • 2,413
  • 2
  • 22
  • 37
  • 3
    Something that your little quote about lazy-loading doesn't mention is that the JVM does the lazy-loading in a _thread-safe_ manner. This is why using this kind of lazy class loading is the preferred method—the JVM handles all the synchronization. – DaoWen Mar 18 '13 at 06:04
  • possible duplicate of [Java: Lazy Initializing Singleton](http://stackoverflow.com/questions/5842273/java-lazy-initializing-singleton) – ecatmur Mar 18 '13 at 11:54

2 Answers2

9

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.
DaoWen
  • 32,589
  • 6
  • 74
  • 101
8

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.

Actually, classloader loads classes (sounds funny) only after you are accessing this classes first time. And only one reason to access enum-singleton class is to get it's instance.

That is why single-element enum type singletone in Java are called lazy - it's value is not initialized before you first time access it.

Similar questions:

Community
  • 1
  • 1
bsiamionau
  • 8,099
  • 4
  • 46
  • 73
  • Thank you for the nice explanation. Here is some more: [why enum singleton](http://javarevisited.blogspot.com.tr/2012/07/why-enum-singleton-are-better-in-java.html?m=1) – Kerem Jan 07 '15 at 02:07