일상&개발 로그

Singleton - DCL과 Demand Holder 본문

개발/개발 일반

Singleton - DCL과 Demand Holder

dskim98 2017. 8. 7. 11:03

Singleton패턴은 하나의 인스턴스만 사용하는 경우 많이 사용되는 패턴입니다.


Singleton패턴을 구현하는 방법에는 여러가지가 있는데, 그 중 DCL과 Demand Holder에 대해 알아보겠습니다.

(DCL은 "lazy-initialization" 시 locking의 overhead를 줄이기 위해 사용합니다.)

기존에 DCL(double-checked-locking)을 많이 사용했었는데, Holder를 사용하면 더 알아보기 쉽게 사용이 가능하다고 합니다. (DCL은 volatile을 사용하지 않으면 Compiler의 reorder에 의해 thread-safe하지 않습니다.)


# DCL

private static volatile Something instance = null;

public static Something getInstance() {
  if (instance == null) {
    synchronized (this) {
      if (instance == null)
        instance = new Something();
    }
  }
  return instance;
}


# Demand Holder

private static class LazySomethingHolder {
  public static Something something = new Something();
}

public static Something getInstance() {
  return LazySomethingHolder.something;
}



# 출처 - http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#whatismm



Comments