this topic을 기반으로, AtomicIntegers를 기반으로 구현 된 Singleton 패턴의 흥미로운 버전을 설명했습니다.이 싱글 톤은 스레드로부터 안전한 것입니까?
- 이 구현 정확하고 스레드 안전하며, 일반적으로 스레드 동기화 및 관리를위한 원자 변수를 사용할 수있다 :
질문은?
- 추가 질문 :이 구현이 스레드로부터 안전하면 실제로 인스턴스 변수에
volatile
수정자가 필요합니까?
public class StrangeSingleton
{
private StrangeSingleton() {};
private static volatile Object instance;
private static AtomicInteger initCounter = new AtomicInteger();
private static AtomicInteger readyCounter = new AtomicInteger();
static Object getInstance()
{
if (initCounter.incrementAndGet() == 1)
{
instance = new Object();
readyCounter.incrementAndGet();
return instance;
}
else if (readyCounter.get() == 1)
{
return instance;
}
else
{
//initialization not complete yet.
//write here some logic you want:
//sleep for 5s and try one more time,
//or throw Exception, or return null..
return null;
}
}
}
UPDATE은 : 민간 생성자,하지만이 아닌 점을 추가했다.
개인 생성자가 누락되었습니다! – Santosh
누구나'new StrangeSingleton()'을 부를 수 있다면 어떻게 싱글 톤이 될 수 있을까요? 인수를 취하지 않는 전용 생성자를 만듭니다. – km1
당신은'AtomicInteger' 대신'AtomicBoolean'을 사용할 수 있습니다. 'compareAndSet()'을 사용하십시오. – Gray