싱글톤 구현 방법 정리
synchronized
방식 (기본 동기화)- 코드:
public class Settings { private static Settings instance; private Settings() { } public static synchronized Settings getInstance() { if (instance == null) { instance = new Settings(); } return instance; } }
- 특징:
- Lazy Loading: 필요할 때 생성.
- Thread-safe:
synchronized
로 스레드 세이프 보장. - 단점: 매 호출마다 락 걸림 → 성능 저하 가능.
- 코드:
Eager Initialization
(이른 초기화)- 코드:
public class Settings { private static final Settings INSTANCE = new Settings(); private Settings() { } public static Settings getInstance() { return INSTANCE; } }
- 특징:
- Eager Loading: 클래스 로드 시 바로 생성.
- Thread-safe: JVM이 초기화 보장.
- 단점: 필요 없어도 무조건 생성 → 메모리 낭비 가능.
- 코드:
Double-Checked Locking
(DCL)- 코드:
public class Settings { private static volatile Settings instance; private Settings() { } public static Settings getInstance() { if (instance == null) { synchronized (Settings.class) { if (instance == null) { instance = new Settings(); } } } return instance; } }
- 특징:
- Lazy Loading: 필요할 때 생성.
- Thread-safe:
volatile
+synchronized
로 보장. - 단점: 복잡하고
volatile
이해 필요.
- 코드:
Static Inner Class
(Holder 패턴)- 코드:
public class Settings { private Settings() { } private static class SettingsHolder { private static final Settings INSTANCE = new Settings(); } public static Settings getInstance() { return SettingsHolder.INSTANCE; } }
- 특징:
- Lazy Loading:
getInstance()
호출 시 생성. - Thread-safe: JVM 클래스 로딩으로 보장.
- 장점: 단순하고 안전, "개꿀" 방식.
- Lazy Loading:
- 코드:
질문 확인
"싱글톤을 구현하는 방법은 1. synchronized, 2. eager initialize, 3. double-checked locking, 4. static inner class 정도 있다 맞아?"
- 네, 딱 맞아요!
- 이 4가지가 싱글톤 구현의 대표적인 방법들이에요.
- 추가로 변형(예:
ReentrantReadWriteLock
DCL)이 있긴 하지만, 기본은 이 4개로 충분합니다.
알잘딱 요약
synchronized
: 간단하지만 느릴 수 있음.- Eager: 빠르고 안전, 근데 필요 없어도 생성.
- DCL: 최적화됐지만 복잡.
- Static Holder: 단순 + Lazy + 안전 → 추천!
'GPT Archiving' 카테고리의 다른 글
싱글톤 패턴 - Double-Checked Locking (volatile) (0) | 2025.03.08 |
---|---|
프로세스, 스레드, 멀티프로세스, 멀티스레드, synchronized (0) | 2025.03.08 |
ReentrantReadWriteLock (0) | 2025.03.06 |
volatile, double-checked-lock (0) | 2025.03.06 |
volatile (0) | 2025.03.06 |