본문 바로가기
프로그래머/프로그래밍

싱글턴 Singleton Pattern

by plog 2010. 6. 9.
개발자들이 여러 디자인 패턴을 사용하겠지만
가장 많이 쓰는 패턴중 하나라고 생각한다. 간편하니깐...
나 또한 그랬지만, 많은 개발자들이 아래와 같이 쓰는것 같다.

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

하지만 위와 같이 구현하면 멀티 쓰레드에서 약간의 문제가 발생할 수 있다.

예를 들어 쓰레드 A와 B가 getInstance 메소드를 거의 동시에 실행 되었을 경우
jvm의 스케쥴링은

1) instance(A) == null 체킹
2) A wait ... instance(B) == null 체킹
3) return instance(B) 리턴.
4) return instance(A) 리턴.

서로 다른 객체가 리턴 될 수 있다.

대안으로 여러 방법이 있지만 쉽게 아래와 같이 하면 방지 할 수 있다.

public class Singleton {
   private static Singleton instance = new Singleton(); // 초기에 생성
    private Singleton() { }
 
    public static Singleton getInstance() {
       return instance;
   }
}






댓글