Java learning notes
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();
}
}
getter
(no property syntax unlike C #)private
. (Same as C #)getInstance ()
is used from multithreadingAs 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
[C # 6.0 ~] Implementation of singleton pattern --Qiita
Java Singleton Design Pattern-Qiita Do not create multiple instances of MSC07-J. Singleton object
Recommended Posts