싱글톤 패턴
1. public class Singleton { => 매번 동기화 해야 하기 때문에 속도가 느림
private static Singleton uniqueInstance;
// 기타 인스턴스 변수
private Singleton() {}
public static synchronized Singleton getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// 기타 메소드
}
2. public class Singleton { => 처음부터 메모리를 소비하고 속도를 높일 수 있음
private static Singleton uniqueInstance = new Singleton();
// 기타 인스턴스 변수
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
// 기타 메소드
}
3. public class Singleton { => 속도와 메모리 두 마리 토끼 잡기
private volatile static Singleton uniqueInstance;
// 기타 인스턴스 변수
// volatile은 언제나 최신값을 가짐(두가지 특징)
// 1. Thread에 변수가 공유되면 각자의 Caching 값을 같고 있다 업데이트 하지만 volatile 변수의 경우
// Caching 하지 않고 바로 메인모메로 영역의 변수로 접근한다.
// 2. 동기화를 지원하여 동시에 여러게의 Thread가 접근할 수 없다.
private Singleton() {}
public static Singleton getInstance() {
if(uniqueInstance == null) { <= 처음에만 동기화하고 다음에는 접근하지 않음
synchronized (Singleton.class) {
if(uniqueInstance == null) { <= Double-checking locking
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
// 기타 메소드
}