2010-06-17 4 views
2
protected synchronized boolean isTimeoutOccured(Duration timeoutDuration) { 
    DateTime now = new DateTime(); 

    if (timeoutOccured == false) { 
     if (new Duration(requestTime.getMillis(), now.getMillis()).compareTo(timeoutDuration) > 0) { 
      timeoutOccured = true; 
     } 
    } 

    return timeoutOccured; 
} 

protected boolean isTimeoutOccured2(Duration timeoutDuration) { 

    return atomicTimeOut.compareAndSet(false, new Duration(requestTime.getMillis(), new DateTime().getMillis()).compareTo(timeoutDuration) > 0); 

} 

답변

1

그것은 부울 표현

new Duration(requestTime.getMillis(), new DateTime().getMillis()).compareTo(timeoutDuration) > 0 

첫 번째 예에서 동기화 된 블록 내부에 있음을 주목할 필요가 있지만 두 번째의 모든 메모리 장벽의 외부. (두 번째 예제에서 표현식의 결과는 atomic compareAndSet 호출에 대한 인수로 전달되지만 표현식 자체의 평가는 메모리 장벽 외부에서 발생합니다.)

따라서 답변은 thread- 그 다른 클래스들 (Duration, DateTime)은 안전합니다. 이것들이 JodaTime 클래스라고 가정하고, javadoc을 잠깐 살펴보면이 클래스가 스레드 안전하고 변경 불가능한 인스턴스를 생성한다는 것을 알 수 있습니다. 따라서 출력은 항상 같아야합니다.

사실,이 계산의 모든 구성 부분이 불변 (모든 DateTime 및 Duration의 인스턴스)이므로, 동기화 또는 원자 compareAndSet을 전혀 사용하지 않아야합니다.

2

예, 원자 기본 요소가 더 효율적입니다.

관련 문제