티스토리 뷰
728x90
반응형
SMALL
싱글톤(Singleton) pattern
- 인스턴스가 1개만 생성되야 하는 경우에 사용되는 패턴.
- 하나의 인스턴스를 메모리에 등록해서 여러 스레드가 동시에 해당 인스턴스를 공유할수 있다.
자바의 싱글톤 패턴
- 생성자를 private으로 정의해서 외부 클래스로부터 인스턴스 생성을 차단.
- 싱글톤 클래스 내부에, private static객체 생성
- public static 메서드를 통해, 외부에서 싱글톤인스턴스에 접근할수 있도록 함
Eager Initialization
클래스가 호출될 때 인스턴스를 생성.
인스턴스를 사용하지않아도 인스턴스를 생성하기때문에 효율이 낮음.
ex)
public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
lazy Initialization
인스턴스를 실제로 사용할 시점에 인스턴스를 생성.
Eager Initialization의 문제였던, 인스턴스의 낭비는 해결되지만, 인스턴스가 생성되지 않은 시점에서 여러 thread가 동시에 getInstance()를 호출하면 문제가 될 수 있다.(single thread 환경에서 사용해야 함)
ex)
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
Thread-Safe Singleton
lazy Initialization의 문제점을 해결할 수 있음.
application의 성능이 많이 저하됨
ex)
public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
728x90
반응형
LIST
'Spring boot study > 기타...' 카테고리의 다른 글
Spring IoC, DI (0) | 2020.11.12 |
---|---|
Controller의 리턴타입 정리 (0) | 2020.07.15 |
댓글