2009년 11월 21일 토요일

[펌] Thread 세이프한 Singleton(싱글톤) 패턴을 JAVA로 구현하는 방법

이글은 자바서비스넷에서 쓰레드 세이프 싱글톤에 대한 계시물을 펌한 글입니다. 계시물을 링크하지 않고 펌 글로 남기는 이유는 계시물이 너무 뒤로 넘어가 있기도 하거니와 댓글 형태의 글을 정리하는 것이 의미가 있다고 생각하기 때문입니다.

 

쓰레드 세이프 싱글톤을 효율적으로 구현하기 위한 DCL(더블체크락킹)방법이 고안되었었습니다. 그러나 그 방법은 자바의 메모리 모델, 캐슁, 코드 최적화의 문제때문에 제대로 동작되지 않는다는 것이 정설입니다.

 

현재 어떤 플랫폼상에서도 완벽히 동작한다고 보장 받을 수 있는 코드는 세가지가 있습니다.

 

1) static 필드에서 초기화 하는 방법

public class Singleton {

   public static final fSingleton = new Singleton();

   private Singleton() {
   }
}

 

2) 모든 createInstance 메소드를 동기화(synchronized)하는 방법

public class Singleton {

   public static final fSingleton = null;

   private Singleton() {
     ....
   }

   public static synchronized Sington createInstance() {
     if ( fSingleton == null ) {

        fSingleton = new Singleton();
     }
     return fSingleton;
   }
}


3) thread-specific 변수를 사용한 방법

  class Singleton {
    private static Singleton theInstance;

    private static final ThreadLocal tlsInstance =
      new ThreadLocal() {
          public Object initialValue() { return createInstance(); }
        };

    public static Singleton getInstance() {
      return (Singleton)tlsInstance.get();
    }

    private static synchronized Singleton createInstance() {
      if (theInstance == null)
        theInstance = new Singleton();
      return theInstance;
    }
  }

댓글 없음:

댓글 쓰기