public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() {
if (singleton == null) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleton = new Singleton();
}
return singleton;
}
}
Thread t1 = new Thread(() -> {
Singleton singleton = Singleton.getInstance();
System.out.println(singleton);
});
Thread t2 = new Thread(() -> {
Singleton singleton = Singleton.getInstance();
System.out.println(singleton);
});
public static synchronized Singleton getInstance() {
if (singleton == null) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleton = new Singleton();
}
return singleton;
}
같은 객체를 참조하는 것을 확인할 수 있다
객체 레벨의 동시성은 적용할 수 없다!
public static Singleton getInstance() {
synchronized (singleton) {
if (singleton == null) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleton = new Singleton();
}
}
return singleton;
}
- 최초에는 락을 걸고 점유할 객체가 존재하지 않기 때문이다.
public static Singleton getInstance() {
synchronized (Singleton.class) {
if (singleton == null) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleton = new Singleton();
}
}
return singleton;
}