package com.lec.java.singleton;
// Java Singleton Pattern
// 1. 내부에 자기 자신의 하나의 인스턴스만 생성해서 사용하다.
// 2. 외부의 생성자 접근을 막는다.
// 3. 오로지 클래스 내부에서만 객체를 관리한다.
public class Singleton {
private static Singleton Instance;
private Singleton() {}
private static Singleton getInstance() {
if (Instance== null) {
Instance = new Singleton();
}
return Instance;
}
} // end class of Singleton
package com.lec.java.singleton;
// 스레드의 동기화 문제 때문에 메소드 자체에 synchronized를 붙어줌
// 이렇식으로 싱글턴을 구현하면 속도가 크게 저하될수있음
// 동시에 여러개의 쓰레드가 이 객체를 사용하면 느려질수 밖에 없음
public class Singleton_MutiThread {
private static Singleton_MutiThread Instance;
private Singleton_MutiThread() {}
private static synchronized Singleton_MutiThread getInstance() {
if (Instance==null) {
Instance = new Singleton_MutiThread();
}
return Instance;
}
} // end class of Singleton_MutiThread
package com.lec.java.singleton;
// 동시에 쓰레드에서 동기화 할때 두개 이상 생성되는 것을 막는 방법
public class Singleton_MutiThread_Sychronized {
private static volatile Singleton_MutiThread_Sychronized Instance;
// volatile : CPU 캐쉬가 아닌 실제 메모리부터 적재하여 사용하는 방법
private Singleton_MutiThread_Sychronized() {}
private static Singleton_MutiThread_Sychronized getInstance() {
if (Instance == null) { // 동시에
synchronized (Singleton_MutiThread.class) {
if (Instance==null) {
Instance = new Singleton_MutiThread_Sychronized();
}
}
}
return Instance;
}
} // end class of Singleton_MutiThread_Sychronized