Singleton & Lazy Initialization
Do you know how to use lazy initialization in Java? There’s already many thread discussing this problem in the comunity, just to conclude here.
Due to the JVM memory model, Double-Checking Locking (DCL) will not work in Java, I’d like to recommend two articles talking about this.
The "Double-Checked Locking is Broken" Declaration
Double-checked locking and the Singleton pattern
There’s another article tell you exactly what synchronized really means, very helpful
Double-checked locking: Clever, but broken
One possible way to use lazy initialization in Java:
- import java.io.*;
- import java.lang.*;
- public class Singleton {
- // private static final Singleton _INSTANCE = new Singleton();
- private Singleton() {
- System.out.println ("Construct Singleton Instance now");
- }
- public static Singleton getInstance() {
- /*
- if(_INSTANCE == null)
- _INSTANCE = new Singleton();
- */
- return SingletonHolder.INSTANCE;
- }
- private void say(String message) {
- System.out.println(message);
- }
- private static class SingletonHolder {
- static Singleton INSTANCE = new Singleton();
- }
- public static void main(String args[]) {
- System.out.println("Hello world!");
- Singleton instance = Singleton.getInstance();
- }
- }
In the end, attach two articles about Singleton in C# in MSDN, there’s no problem using DCL in C#.
Exploring the Singleton Design Pattern
More entries about : none
Maybe you are also interested in the following entries: