Singleton

Description

Singleton

is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton.

You job is to implement a getInstancemethod for given class, return the same instance of this class every time you call this method.

Example

In Java:

    A a = A.getInstance();
    A b = A.getInstance();

a should equal to b.

Challenge

If we call getInstance concurrently, can you make sure your code could run correctly?

Solution

创建静态instance成员,每次都返回此静态成员。

Traditional Singleton: Lazy Initialization

/**
* This reference program is provided by @jiuzhang.com
* Copyright is reserved. Please indicate the source for forwarding
*/

class Solution {
    /**
     * @return: The same instance of this class every time
     */
    public static Solution instance = null;
    public static Solution getInstance() {
        if (instance == null) {
            instance = new Solution();
        }
        return instance;
    }
};

The getSingleton()method is attempting to lazily initializing the SINGLETON instance, but it has the following problems:

  • Access to the variable is not synchronized

  • The variable is not volatile

  • You are not using double checked locking

so a race condition MAY cause two instances to be created.

Source: https://stackoverflow.com/questions/12878012/concurrent-calls-of-singleton-class-methods

About Thread Safety:

https://crunchify.com/thread-safe-and-a-fast-singleton-implementation-in-java/

Auto ThreadSafe Singleton Pattern:

package com.crunchify.tutorials;

public class ThreadSafeSingleton {

    private static final Object instance = new Object();

    protected ThreadSafeSingleton() {
    }

    // Runtime initialization
    // By defualt ThreadSafe
    public static Object getInstance() {
        return instance;
    }
}

Through this approach we provide the necessary thread-safety, as the Singleton instance is created at class-load time. Any subsequent calls to the getInstance() method will return the already created instance. Furthermore, the implementation is optimized as we’ve eliminated the need for checking the value of the Singleton instance, i.e. instance == null.

Simple Singleton Pattern: (Lazy Initialization + ThreadSafe with synchronized block)

package com.crunchify.tutorials;

public class CrunchifySingleton {

    private static CrunchifySingleton instance = null;

    protected CrunchifySingleton() {
    }

    // Lazy Initialization (If required then only)
    public static CrunchifySingleton getInstance() {
        if (instance == null) {
            // Thread Safe. Might be costly operation in some case
            synchronized (CrunchifySingleton.class) {
                if (instance == null) {
                    instance = new CrunchifySingleton();
                }
            }
        }
        return instance;
    }
}

It is clear from the example that the traditional approach is not thread-safe , as it’s possible that before a thread creates the Singleton instance, another thread proceeds to the instantiation part of the code (i.e. instance = new Object();), because the condition instance == null is still true.

StackOverflow Answer:

What is an efficient way to implement a singleton pattern in Java? [closed]

https://stackoverflow.com/a/16580366

Thread Safe Singleton in Java

https://www.journaldev.com/171/thread-safety-in-java-singleton-classes-with-example-code

package com.journaldev.designpatterns;

public class ASingleton {

    private static ASingleton instance = null;

    private ASingleton() {
    }

    public static ASingleton getInstance() {
        if (instance == null) {
            instance = new ASingleton();
        }
        return instance;
    }

}

-

There are three ways through which we can achieve thread safety.

  1. Create the instance variable at the time of class loading. Pros:

    • Thread safety without synchronization

    • Easy to implement

    Cons:

    • Early creation of resource that might not be used in the application.

    • The client application can’t pass any argument, so we can’t reuse it. For example, having a generic singleton class for database connection where client application supplies database server properties.

  2. Synchronize the getInstance() method Pros:

    • Thread safety is guaranteed.

    • Client application can pass parameters

    • Lazy initialization achieved

    Cons:

    • Slow performance because of locking overhead.

    • Unnecessary synchronization that is not required once the instance variable is initialized.

  3. Use synchronized block inside the if loop and volatile variable Pros:

    • Thread safety is guaranteed

    • Client application can pass arguments

    • Lazy initialization achieved

    • Synchronization overhead is minimal and applicable only for first few threads when the variable is null.

    Cons:

    • Extra if condition

Using 3rd approach:

package com.journaldev.designpatterns;

public class ASingleton {

    private static volatile ASingleton instance;
    private static Object mutex = new Object();

    private ASingleton() {
    }

    public static ASingleton getInstance() {
        ASingleton result = instance;
        if (result == null) {
            synchronized (mutex) {
                result = instance;
                if (result == null)
                    instance = result = new ASingleton();
            }
        }
        return result;
    }

}

Last updated