Moon Light Box

Time is Money

Java - Singleton Pattern

| Comments

Singleton pattern can make a class to be created the only one instance.

First, writing a singleton class.

public class Singleton {
    public Singleton() {
    }
}

Then you will do this to use it. And this way causes duplicate instances when you call new many times.

Singleton mSingleton = new Singleton();

So we modify design to this.

public class Singleton {
    private Singleton() {
    }
   
    public static Singleton getInstance() {
        return new Singleton();
    }
}

But it still happened duplicate instances when we call several times of Singleton.getInstance();.

Next, we modify it again.

public class Singleton {
    private static Singleton mSingleton;
    private Singleton() {
    }
   
    public static Singleton getInstance() {
        if (null == mSingleton) {
            mSingleton = new Singleton();
        }
        return mSingleton;
    }
}

Do we finish it? No. Let us think about multi-thread situation instead of single-thread.

Thread1: if (null == mSingleton) // This will be true.
Thread2: if (null == mSingleton) // This will be true.

Thread1: mSingleton = new Singleton();
Thread2: mSingleton = new Singleton();

Thread1: return mSingleton;
Thread2: return mSingleton; 

Happened duplicate instances again! Let us added synchronized to protect.

public class Singleton {
    private static Singleton mSingleton;
    private Singleton() {
    }
   
    public static synchronized Singleton getInstance() {
        if (null == mSingleton) {
            mSingleton = new Singleton();
        }
        return mSingleton;
    }
}

Now, duplicate instances problem is solved. And the new problem is performance.
If there are many threads running, a thread need wait front thread until it finished work.
So we can do this. Initialed the Singleton class only once when program on started.

public class Singleton {
    private static Singleton mSingleton = new Singleton();
    private Singleton() {
    }
   
    public static Singleton getInstance() {
        return mSingleton;
    }
}

Comments

comments powered by Disqus