Singleton
guarantee a class only have one instance, provide global access to the instance
Multiple threading
S1
public class Singleton {
private final Singleton instance;
private Singleton() {
// dosth
};
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
};
}
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
how to handle the critical section
option1: add synchronized keyword
option2: design
option3: double check
S2:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
// do sth;
}
public static Singleton getInstance() {
return INSTANCE;
}
}
No comments:
Post a Comment