티스토리 뷰

hacking/java

singleton과 lazy loading...

iolo 2007. 1. 28. 16:54
싱글톤 패턴의 전형적인 자바 구현:
  1. public class Singleton {
  2.   static Singleton instance;
  3.   public static synchronized Singleton getInstance() {
  4.     if (instance == null) {
  5.       instance == new Singleton();
  6.     }
  7.     return instance;
  8.   }
  9. }
위의 구현의 문제점은 getInstancesynchronized는 것이다.

그래서 좀 지저분하지만 현실적인 해결책으로:
  1.   public static Singleton getInstance() {
  2.     if (instance == null) {
  3.         synchronized (Singleton.class) {
  4.            if (instance == null) {
  5.               instance == new Singleton();
  6.            }
  7.         }
  8.     }
  9.     return instance;
  10.   }
이런 식의 코드를 쓰곤 했는데...

여기~ 더 멋진 방법이 있다!
  1. public class Singleton {
  2.   static class SingletonHolder {
  3.     static Singleton instance = new Singleton();
  4.   }
  5.   public static Singleton getInstance() {
  6.     return SingletonHolder.instance;
  7.   }
  8. }

스프링까지 동원하기 뭣한 작은 프로그램이나, 프레임워크와 독립적으로 동작해야하는 유틸리티 클래스에서 유용하게 써먹을 수 있겠다.

'hacking > java' 카테고리의 다른 글

Maven2와 Eclipse/WTP 함께쓰기 (2)  (0) 2007.09.13
Maven2와 Eclipse/WTP 함께쓰기  (0) 2007.09.11
Java6 XMLOutputFactory 유감  (2) 2007.01.15
XML Exodus...  (3) 2007.01.07
아니~ 버~ㄹ써! Java6~  (0) 2006.12.12
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함