싱글톤

요즘 많이 쓰는 싱글톤 for Java

더블락체크(보통), 빌퍼지(good, mostly used), enum(better for java)
  1. 더블락체크
    1. lazy initialization을 하는데 함수에 synchronized를 쓰는게아니라 함수 안에서 null체크를 한번 하고나서 null인 경우에만 synchronized를 쓰게함
    2. null이 아닐때눈 synchronized를 호출하지 않아 성능 향상
  2. 빌퍼지(Bill puge)
    1. A.K.A. Initialization-on-demand holder
    2. Class안에 LazyHolder static class를 선언하고 static final 인스턴스를 생성
    3. getInstance시에 위의 static class안에 있는 인스턴스를 리턴
    4. 장점
      1. Class안에 static 변수가 없기때문에 lazy initialization이 구현됨
      2. 쓰레드세이프한 이유:  And since the initialization phase writes the static variable INSTANCE in a serial operation, all subsequent concurrent invocations of the getInstance will return the same correctly initialized INSTANCE without incurring any additional synchronization overhead.
        1. final이기 때문에!
    5. public class BillPughSingleton {
      
          private BillPughSingleton(){}
          
          private static class SingletonHelper{
              private static final BillPughSingleton INSTANCE = new BillPughSingleton();
          }
          
          public static BillPughSingleton getInstance(){
              return SingletonHelper.INSTANCE;
          }
      }
  3. enum
    1. 위에 class로 작성된 싱글톤들은 결국 Refelection을 사용하면 해체됨.
    2. enum은 JVM이 보장하는 only 1번만 생성됨 그래서 enum으로 싱글톤을 사용하자
    3. public enum EnumSingleton {
      
          INSTANCE;
          
          public static void doSomething(){
              //do something
          }
      }

댓글

이 블로그의 인기 게시물

XPath와 Appium과 Python

Gradle