Java

Java_ Lazy Singleton

JunsC 2024. 8. 25. 18:03
728x90

싱글톤 사용은 유용하다고 느꼈다.

앱을 만들때 공통적으로 사용하는 api 라든지 , 메소드 등 반복적인 사용이 필요한 부분들이 있는데 이걸 계속 생성자로 생성해주거나 단순히 메모리에 올려 전역으로 사용한다면 성능상 문제가 생길것이다.

이러한 부분을 방지하기 위해 싱글톤이 있었고 싱글톤은 메모리에 올림으로 인한 누수 나 지속적인 생성사용을 방지한다.

이때, lazy singleton 방식이 있는데 이는 기존 싱글톤 방식에서 더욱 효율적인 방법으로 메모리를 다루는다고 보면 된다.

밑의 코드는 기본적인 싱글톤 코드이다.

public class Singleton {

private static Singleton instance;

private Singleton() {

 }

public static synchronized Singleton getInstance() {

if (instance == null) {

instance = new Singleton();

}

return instance;

}

 

728x90

synchronized 로 동기화를 적용하고 있기에 스레드 관련해서 안정성을 부여했다.

 

그리고 밑에 코드는 아까 언급한 lazy_singleton 방식이라 생각하면 된다.

더블체크를 하는 기능을 추가한것이다.

public class Singleton {

private static volatile Singleton instance;

private Singleton() {

}

public static Singleton getInstance() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton(); }

}

}

return instance; }

 }

 

 

혹은 내가 사용하고 있는 Inner class 방식이다.

public class Singleton {

private static class SingletonHolder {

private static final Singleton INSTANCE = new Singleton();

}

private Singleton() {

}

public static Singleton getInstance() {

return SingletonHolder.INSTANCE;

}  

}

 

728x90