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);
}
views:
87answers:
2It's worth noting that the boolean expression
new Duration(requestTime.getMillis(), new DateTime().getMillis()).compareTo(timeoutDuration) > 0
is inside a synchronized block in your first example, but outside of any memory barrier in the second. (In the second example, the result of the expression is passed as an argument to the atomic compareAndSet call, but the evaluation of the expression itself occurs outside of any memory barrier.)
Therefore, the answer depends on how thread-safe those other classes (Duration, DateTime) are. I assume these are JodaTime classes, and a quick glance at javadoc indicates those classes produce thread-safe and immutable instances, so for that reason the output should always be the same.
In fact, given that all of the constituent parts of this calculation are immutable (all the instances of DateTime and Duration), you should be able to get away with no synchronization or atomic compareAndSet at all.