싱글톤
요즘 많이 쓰는 싱글톤 for Java
더블락체크(보통), 빌퍼지(good, mostly used), enum(better for java)
- 더블락체크
- lazy initialization을 하는데 함수에 synchronized를 쓰는게아니라 함수 안에서 null체크를 한번 하고나서 null인 경우에만 synchronized를 쓰게함
- null이 아닐때눈 synchronized를 호출하지 않아 성능 향상
- 빌퍼지(Bill puge)
- A.K.A. Initialization-on-demand holder
- Class안에 LazyHolder static class를 선언하고 static final 인스턴스를 생성
- getInstance시에 위의 static class안에 있는 인스턴스를 리턴
- 장점
- Class안에 static 변수가 없기때문에 lazy initialization이 구현됨
- 쓰레드세이프한 이유: 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.
- final이기 때문에!
public class BillPughSingleton { private BillPughSingleton(){} private static class SingletonHelper{ private static final BillPughSingleton INSTANCE = new BillPughSingleton(); } public static BillPughSingleton getInstance(){ return SingletonHelper.INSTANCE; } }
- enum
- 위에 class로 작성된 싱글톤들은 결국 Refelection을 사용하면 해체됨.
- enum은 JVM이 보장하는 only 1번만 생성됨 그래서 enum으로 싱글톤을 사용하자
public enum EnumSingleton { INSTANCE; public static void doSomething(){ //do something } }
댓글
댓글 쓰기