Overview

전역 변수를 사용하지 않고 하나의 객체만 생성하고 생성된 객체를 어디서나 참조하는 패턴
하나의 인스턴스만 생성하는 역할을 하며 Getinstance 메서드는 모든 클라이언트에 동일한 인스턴스를 반환하는 것입니다.

다중 스레드에서 사용되는 유틸리티 클래스의 경우 모든 스레드에서 객체를 생성하지 않고 이미 만들어진 객체를 가져와서 사용하는 것이 메모리와 CPU에서 더 좋습니다.
Calendar.getInstance()에 대한 Java의 캘린더 클래스 개체를 사용하여 사용합니다.
시간대를 표현하기 위해 새로운 객체를 생성할 필요가 없기 때문입니다.

단, Calendar 클래스를 사용하기 위해서는 Client 프로그램에서 new Calendar()를 호출하지 않도록 주의한다.
이를 해결하는 방법은 생성자가 외부에서 호출되는 것을 방지하는 것입니다.
Calendar 클래스의 생성자를 private로 선언합니다.

문제는 여러 스레드에서 Printer 클래스를 사용할 때 하나 이상의 인스턴스가 생성된다는 것입니다.

경우에 따라 경쟁 조건이 생성됩니다.
메모리와 같은 동일한 자원을 사용하기 위해 2개 이상의 쓰레드를 사용하는 현상


Printer 인스턴스가 아직 생성되지 않은 경우 Sweep 1은 getPrinter 메서드의 if 문을 실행하여 인스턴스가 이미 생성되었는지 확인합니다. 현재 프린터 변수는 NULL입니다.


스레드 1이 생성자를 호출하면 스레드 2는 인스턴스를 만들기 전에 if 문을 실행하여 Printer 변수가 NULL인지 확인합니다. 현재 프라이머 변수는 NULL이므로 인스턴스를 생성하는 생성자를 호출하는 코드를 실행합니다.


스레드 1은 스레드 2와 마찬가지로 인스턴스를 생성하는 코드를 실행하고 결과적으로 프린터 클래스의 두 인스턴스가 생성됩니다.

 

Structure

https://ko.wikipedia.org/wiki/%EC%8B%B1%EA%B8%80%ED%84%B4_%ED%8C%A8%ED%84%B4

 

Code Example

package com.example.design.pattern;

public class MySingleton {
	private volatile static MySingleton instance = new MySingleton();

	private MySingleton() {
	}

	public static MySingleton getInstance() {
		if (instance == null) {
					instance = new MySingleton();
		}
		
		return instance;
	}
}
// I didn't call at the start of the program, but there are issues allocated to memory.
package com.example.design.pattern;

public class MySingleton {
	private volatile static MySingleton instance = null;

	private MySingleton() {
	}

	public synchronized static MySingleton getInstance() {
		if (instance == null) {
					instance = new MySingleton();
		}
		
		return instance;
	}
}
// Synchronized on the method can be locked and slowly slow in multiple thread environments.
package com.example.design.pattern;

public class MySingleton {
	private volatile static MySingleton instance = null;

	private MySingleton() {
	}

	public static MySingleton getInstance() {
		if (instance == null) {
			synchronized (MySingleton.class) {
				if (instance == null) {
					instance = new MySingleton();
				}
			}
		}
		
		return instance;
	}
}
// NULL checks twice to solve the performance deterioration issues caused by LOCK.

 

Console Result

1234
1234

 

Conclusion

N/A

728x90

+ Recent posts