[Java] Singleton pattern

Java learning notes

Singleton pattern

Basic (premise of use from single thread)

SingletonClass.java


package com.company;

public class SingletonClass {
    private static SingletonClass instance = new SingletonClass();

    private SingletonClass() {}

    public static SingletonClass getInstance() {
        return instance;
    }
}

Main.java


package com.company;

public class Main {
    public static void main(String[] args) {
        SingletonSample obj = SingletonSample.getInstance();
    }
}

Multi-thread support

As mentioned above, instances are created when the class is first used, not when it is loaded, so if you allow multithreaded calls to getInstance (), you will have multiple instances. May be created.

The following can be mentioned as a countermeasure method.

Use synchronized modifier


class Singleton {
    static Singleton instance = null;
    public static synchronized Singleton getInstace() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Initialize-on-Demand_Holder_Class pattern


class Singleton {
    private Singleton(){}

    public static Singleton getInstace() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
}

reference Design pattern "Singleton" --Qiita Do not create multiple instances of MSC07-J. Singleton object

Relation

[C # 6.0 ~] Implementation of singleton pattern --Qiita

reference

Java Singleton Design Pattern-Qiita Do not create multiple instances of MSC07-J. Singleton object

Recommended Posts

[Java] Singleton pattern
Singleton Pattern
Singleton pattern
[Java] Strategy pattern
java callback pattern
Design pattern ~ Singleton ~
[Java] Adapter pattern
Java pattern memo
My DAO pattern (Java)
[Java] About Singleton Class
Builder pattern (Effective Java)
Java Lambda Command Pattern
Java design pattern summary
[Design pattern] Java core library
Java
Enum Strategy pattern in Java
[Java] Draw a simple pattern
Java
Understand the Singleton pattern by comparing Java and JavaScript code
JNA (Java Native Access) pattern collection
Java Calendar is not a singleton.
Java beginner design pattern (Factory Method pattern)
Prototype pattern
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
Memento Pattern
[Java] Annotation
[Java] Module
Java array
Mediator pattern
Iterator pattern
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Composite pattern
Java methods
Java method
java (constructor)
Java array
Observer Pattern
java (override)
java (method)
Builder pattern
Java Day 2018
Java string
Bridge Pattern
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Command Pattern
Java (set)
[Java] compareTo
Studying Java -5
Builder Pattern
java reflexes
java (interface)
Java memorandum