Singleton In Java

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.

Identification: Singleton can be recognized by a static creation method, which returns the same cached object.

Singleton.java

public final class Singleton {
    private static Singleton instance;
    public String value;

    private Singleton(String value) {
        // For initializing object slowly
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        this.value = value;
    }

    public static Singleton getInstance(String value) {
        if (instance == null) { // Checks if instance of object not already existing
            instance = new Singleton(value);
        }
        return instance;
    }
}

DemoSingleton.java

public class DemoSingleton{

public static void main(String[] args) { System.out.println("If you see the same value, then singleton was reused" + "\n" + "RESULT:" + "\n"); Singleton singleton = Singleton.getInstance("Summer"); Singleton anotherSingleton = Singleton.getInstance("Winter"); System.out.println(singleton.value); System.out.println(anotherSingleton.value); } }

Result :

If you see the same value, then singleton was reused

RESULT:

Summer
Summer

Thread-safe Singleton 

Singleton.java
public final class Singleton {
    // The field must be declared volatile so that double check lock would work
    // correctly.
    private static volatile Singleton instance;

    public String value;

    private Singleton(String value) {
        this.value = value;
    }

    public static Singleton getInstance(String value) {
        // double-checked locking (DCL) to prevent race condition between multiple threads
        Singleton result = instance;
        if (result != null) {
            return result;
        }
        synchronized(Singleton.class) {
            if (instance == null) {
                instance = new Singleton(value);
            }
            return instance;
        }
    }
ClientMultiThread.java

public class ClientMultiThread {
    public static void main(String[] args) {
        System.out.println("Here its guaranteed it will return same singleton instance" + "\n" +
+ "\n\n" + "RESULT:" + "\n"); Thread threadSummer = new Thread(new ThreadSummer()); Thread threadWinter = new Thread(new ThreadWinter()); threadSummer.start();
threadWinter.
start();
}
static class ThreadSummer implements Runnable {
@Override public void run() { Singleton singleton = Singleton.getInstance("Summer"); System.out.println(singleton.value); } } static class ThreadWinter implements Runnable {
@Override public void run() { Singleton singleton = Singleton.getInstance("Winter"); System.out.println(singleton.value); } } }
OUTPUT:
 Here its guaranteed it will return same singleton instance

RESULT:

Summer
Summer

Post a Comment

Previous Post Next Post