2012-11-19 4 views

답변

4

을 쓸 수 고정되지 않습니다. 자바 5에서는이 관용구가 깨 졌음을 명확하게 명시했으며 이것이 최종 평결이었다. 느리게 인스턴스 필드를 초기화하는 적절한 방법은 다른 유사라는 관용구를 포함하십시오 더블 체크 관용구 :

// Double-check idiom for lazy initialization of instance fields. 
private volatile FieldType field; 
FieldType getField() { 
    FieldType result = field; 
    if (result == null) { // First check (no locking) 
    synchronized(this) { 
     result = field; 
     if (result == null) // Second check (with locking) 
     field = result = computeFieldValue(); 
    } 
    } 
    return result; 
} 

참조 : 조쉬 블로흐, 효과적인 자바. this Oracle technetwork interview with Josh Bloch도 참조하십시오.

8

간단한 구글은 좋은 생각을 여전히 (마르코의 답변을 참조) 특정 방법을 사용하는 경우

  • 이 그것은 자바 5에서 수정 된 것을
  • 그것을 보여줍니다 없습니다. 종종 간단한 enum이 더 나은 해결책입니다. 대신 쓰기

    public final class Singleton { 
        // Double-check idiom for lazy initialization of instance fields. 
        private static volatile Singleton instance; 
    
        private Singleton() { 
        } 
    
        public static Singleton getInstance() { 
         Singleton result = instance; 
         if (result == null) { // First check (no locking) 
          synchronized (Singleton.class) { 
           result = instance; 
           if (result == null) // Second check (with locking) 
            instance = result = new Singleton(); 
          } 
         } 
         return result; 
        } 
    } 
    

당신은 그냥 고정되지 않은, 아니

public enum Singleton { 
    // Thread safe lazy initialization of instance field. 
    INSTANCE 
}