1.4에서 이중 확인 문제가 발생했습니다. http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html 나중에 JDK에서 수정 되었습니까?1.6 또는 1.7에서 이중 확인 문제가 해결 되었습니까?
0
A
답변
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
}
게시 한 것과 동일한 읽기에서 더 이동하면 Java 5에서 수정 되었음이 표시됩니다. –