开发者

Do these methods have same output?

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 atom开发者_StackOverflow社区icTimeOut.compareAndSet(false, new Duration(requestTime.getMillis(), new DateTime().getMillis()).compareTo(timeoutDuration) > 0);

}


Yes, but atomic primitives are more efficient.


It'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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜