/**
* 멀티스레딩이 해결되지 않은 싱글톤 생성 방식
*/
public class Singleton_step1_with_problem {
/**
* 유일한 인스턴스를 저장하기 위한 정적 변수
*/
private static Singleton_step1_with_problem uniqueInstance;
/**
* 생성자를 private으로 선언했기 때문에 해당 클래서에서만 인스턴스를 만들 수 있다
*/
private Singleton_step1_with_problem() {}
public static Singleton_step1_with_problem getInstance() {
if (uniqueInstance == null) uniqueInstance = new Singleton_step1_with_problem();
return uniqueInstance;
}
}
동기화를 진행하지 않았을 때 문제점
public class Singleton_step2_synchronized {
/**
* 유일한 인스턴스를 저장하기 위한 정적 변수
*/
private static Singleton_step2_synchronized uniqueInstance;
/**
* 생성자를 private으로 선언했기 때문에 해당 클래서에서만 인스턴스를 만들 수 있다
*/
private Singleton_step2_synchronized() {}
/**
* synchronized 동기화 처리 -> 멀티스레드 해결
*/
public static synchronized Singleton_step2_synchronized getInstance() {
if (uniqueInstance == null) uniqueInstance = new Singleton_step2_synchronized();
return uniqueInstance;
}
}
public class Singleton_step3_create_jvm {
/**
* 유일한 인스턴스를 저장하기 위한 정적 변수
*/
private static final Singleton_step3_create_jvm uniqueInstance = new Singleton_step3_create_jvm();
/**
* 생성자를 private으로 선언했기 때문에 해당 클래서에서만 인스턴스를 만들 수 있다
*/
private Singleton_step3_create_jvm() {}
public static Singleton_step3_create_jvm getInstance() {
return uniqueInstance;
}
}
public class Singleton_step4_DCL {
/**
* 유일한 인스턴스를 저장하기 위한 정적 변수
* volatile을 통한 동기화 변수 선언
*/
private volatile static Singleton_step4_DCL uniqueInstance;
/**
* 생성자를 private으로 선언했기 때문에 해당 클래서에서만 인스턴스를 만들 수 있다
*/
private Singleton_step4_DCL() {}
/**
* synchronized 동기화 처리 -> 멀티스레드 해결
*/
public static synchronized Singleton_step4_DCL getInstance() {
if (uniqueInstance == null) uniqueInstance = new Singleton_step4_DCL();
return uniqueInstance;
}
}