목록 3.15. 제대로 게시되지 않으면 실패 위험에 처한 클래스. javac의이
if (n != n)
를 최적화하지 왜연습에서 책 자바 동시성의 예를 이해하는 방법?
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}
나의 첫번째 질문은?
다음은 예
public class TestSync {
private int n;
public TestSync(int n) {
this.n = n;
}
public void assertSanity() {
if(n!=n)
throw new AssertionError("This statement is false");
}
private static TestSync test;
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
if(test == null) test = new TestSync(2);
else test = null;
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
if(test != null)
try {
test.assertSanity();
} catch (NullPointerException e) {
}
}
}
}).start();
}
}
내 데모입니다 그리고 내 두 번째 질문은 내가 옳은 일을 했습니까입니까? 데모를 실행할 때 예외가 발생하지 않기 때문입니다.
UPDATE 내 첫 번째 질문에 대한
1.Addition : 나는 if(false)
-if(n!=n)
을 최적화하고 축소 할 javac의를 thinked javap -c TestSync.class
public void assertSanity();
Code:
0: aload_0
1: getfield #3 // Field n:I
4: aload_0
5: getfield #3 // Field n:I
8: if_icmpeq 21
11: new #4 // class java/lang/AssertionError
14: dup
15: ldc #5 // String This statement is false
17: invokespecial #6 // Method java/lang/AssertionError."<init>":(Ljava/lang/Object;)V
20: athrow
21: return
.
2. 을 추가 한 이유는 if(test != null)
입니까?
test
필드는 다른 스레드가 일 수 있다고 생각하므로 if(test!=null)
뒤에 있습니다.
무엇이 질문입니까? javac이 그것을 최적화하지 않는다는 것을 어떻게 알 수 있습니까? null 객체에 대한 if 문 내부에서 NullPointerException에 대한 try catch가있는 이유는 무엇입니까? –
@ cricket_007 이미 내 질문 업데이트 – dcnh35
내가 틀릴 수도 있지만 '테스트'가 '동기화'되어야합니까? –