Blog Content

    티스토리 뷰

    싱글턴 패턴

    @저널데브

    http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples


    @저널데브 해석한 곳

    https://blog.seotory.com/post/2016/03/java-singleton-pattern


    @싱글턴을 사용하는 목적

    오직 하나의 객체가 필요할 때


    @싱글턴을 사용하며 생긴 문제가 멀티스레드 환경의 동기화 문제!


    @그렇다면 싱글턴 패턴은 언제 사용해야 할까?

    ...?!!!!!!!????


    -A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.

    전체 응용 프로그램에서 공유하는 리소스에 대한 액세스를 관리 할 때는 싱글 톤을 사용해야하며 잠재적으로 동일한 클래스의 인스턴스가 여러 개있는 경우 파괴적입니다. 이런 종류의 패턴이 중요 할 수있는 곳 중 하나 인 공유 리소스에 대한 스레드 안전 액세스가 아주 좋은 예임을 확인하십시오.



    @싱글턴 패턴의 특징

    1. 생성자가 private

    2. 인스턴스를 반환하는 메서드

    3. ??


    @Thread Safe Singleton

    이 방식은 메서드를 동기화 한 방식이다. 그런데 싱글턴패턴은 객체가 생성될 때만 동기화를 하면 되는데 이 메서드에 접근할 때마다 동기화를 하게 되어 많은 메모리를 잡아먹는다. 그래서 개선한 것이 메서드 안에서 동기화를 해 주는 것이다. 이것이 Double Checked Locking 방법이다.


    기본 ThreadSafeSingleton 방식

    package com.journaldev.singleton;
    
    public class ThreadSafeSingleton {
    
        private static ThreadSafeSingleton instance;
        
        private ThreadSafeSingleton(){}
        
        public static synchronized ThreadSafeSingleton getInstance(){
            if(instance == null){
                instance = new ThreadSafeSingleton();
            }
            return instance;
        }
        
    }


    Double Checked Locking 방식

    public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
        if(instance == null){
            synchronized (ThreadSafeSingleton.class) {
                if(instance == null){
                    instance = new ThreadSafeSingleton();
                }
            }
        }
        return instance;
    }

    --> 찾아보니, 이전에 빌더패턴에서 보았던 SessionBuilder에도 이 방식을 사용하고 있었다.



    싱글턴 패턴이 사용된 코드 리뷰


    @JDK의 java.lang의 Runtime 클래스

    getRuntime()에서 인스턴스를 얻어온다.


    별거 없다...



    @JDK의 awt의 Desktop 클래스

    -getDesktop()으로 인스턴스를 가져온다.

    -또 얘는 메서드 동기화를 했다.

    -얘는 인스턴스가 사용되는 시점에 객체를 생성하는 LazyInitialization 방법이다.







    '디자인 패턴' 카테고리의 다른 글

    옵저버 패턴 Observer Pattern  (390) 2017.01.07
    프로토타입 패턴  (388) 2016.12.24
    자바 디자인 패턴 참고 자료 및 정리  (403) 2016.11.20

    Comments