Singleton Pattern
정의
해당 클래스의 인스턴스가 하나만 만들어 지고, 어디서든 그 인스턴스에 접근할 수 있도록 하기 위한 패턴입니다.

싱글톤 패턴 예
public class Singleton {
    private static Singleton instance;

    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

위와 같이 사용 할 경우 멀티 스레드 환경에서 여러개의 인스턴스가 생성 될 수 있습니다. 그래서 getInstance() 에 synchronized 를 사용해서 스레드 환경에서 발생되는 문제를 해결 할 수 있습니다. 문제는 해결되긴 하지만 동기화를 하면 속도가 느려지는 문제가 발생 합니다. 동기화가 꼭 필요한 시점은 인스턴스를 만드는 그 시점 한 번 뿐이지만 아래와 같이 사용을 하면 불필요한 오버헤드만 증가됩니다.
public class Singleton {
    private static Singleton instance;	
    private Singleton() {}	
    /**
     * getInstance()에 synchronized 키워드만 추가하면 한 스레드가 
     * 메소드 사용을 끝내기 전까지 다른 스레드는 기다려야 합니다.
     * 즉, 두 스레드가 이메소드를 동시에 실행시킬 수 없습니다.
     */
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

싱글톤을 사용하기 위한 방법
1. getInstance() 의 속도가 그리 중요하지 않으면 그냥 동기화를 사용한다.
2. 인스턴스를 필요할 때 생성하지 말고 처음부터 만들어 버린다.

public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}

3. DCL(Double-Checking Locking)을 써서 getInstance()에서 동기화되는 부분을 줄인다.
public class Singleton {
    // 1.5 이전의 버전에서는 volatile 키워드를 사용 할 수 없습니다.
    private volatile static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            // 이 방법을 사용 하면 처음에 한번만 동기화가 된다.
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Posted by outliers
,