본문 바로가기
프로그래밍/JAVA

java 싱글톤 패턴(Singleton pattern) 사용 방법

by 원피스랜드 2020. 12. 30.
반응형

싱글톤 패턴 이란??

애플리케이션이 시작될 때 어떤 클래스가 최초 한번만 메모리를 할당 하여(Static)

메모리에 인스턴스를 만들어 사용하는 디자인패턴이에요.

단하나의 인스턴스를 만든다고 생각하시면 되요.

 

싱글톤을 구현하는 방법은 여러가지 에요.

SingletonHolder 사용하여 싱글톤을 구현하는 방법에 대해 포스팅 할게요.

제가 본 여러가지 싱글톤 패턴중에 방법들중에서 가장 안정적이고, 완벽하다고 해요.

 

- wiki 백과

Initialization-on-demand holder idiom

 

University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[7] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization-on-demand holder idiom is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.

 

The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).

 

* SingletonHolder 패턴 특징

1. 아래 패턴은 특별한 언어구조가 필요 하지않다 ( 예를 들면 volatile or synchronized )

2. 자바의 모든 버전에서 작동한다.  

3. 스레드에 안전하다. 

 ( 즉 해당 객체에 동시접근을 해도, 싱글톤의 인스턴스만 리턴해줄수 있다는 이야기로 해석했다.

아니면 댓글 좀 )

4. inner class 의 getInstance가 호출되는 순간이전에는 class로더에 의해 생성되지 않는다.

 

 

*  singleton 구현 코드

public class Singleton {

        // Private constructor. Prevents instantiation from other classes.
        private Singleton() { }

        /**

         * Initializes singleton.

         *

         * SingletonHolder is loaded on the first execution of Singleton.getInstance()

         * or the first access to SingletonHolder.INSTANCE, not before.

         */

        private static class SingletonHolder {

                private static final Singleton INSTANCE = new Singleton();

        }

        public static Singleton getInstance() {

                return SingletonHolder.INSTANCE;

        }
}

 

 

 

참고 문서

 

양코 형의 블로그에서 발췌 했다.

http://www.brucalipto.org/java/singleton-pattern-singletonholder/

 

Writing a singleton is not that hard but writing it the right way may not be all that trivial. I wrote hundreds singletons in my developer life and yesterday I found, thanks to a Wikipedia post, what I think is the perfect solution. The solution is not mine but I report it here for future reference:

 

양코형이 개발하면서 수백개의 싱글톤을 썻는데,

어제 이 패턴을 찾았고  패턴이 완벽 하다고 한다.

위키 백과 게시물한테 고맙단다.

 

 

싱글톤 참고 wiki URL

http://en.wikipedia.org/wiki/Singleton_pattern

 

Singleton pattern - Wikipedia

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from

en.wikipedia.org

 

반응형

댓글