这是我上一个问题的延续——重构同步块保持执行顺序不变
我在一个我想要取消的功能中有一个同步块,还有其他东西可以减少争用并提高性能。
public CallCompletion startCall()
{
long currentTime;
Pending pending = null;
long lastStartTime = _lastStartTime.get();
currentTime = _clock.currentTimeMillis();
synchronized (_lock)
{
_lastStartTime = currentTime;
_tracker.getStatsWithCurrentTime(currentTime);
_sumOfOutstandingStartTimes += currentTime;
_callStartCountTotal++;
_tracker._callStartCount++;
if (_callStartsInLastSecondTracker != null) _callStartsInLastSecondTracker.addCall();
_concurrency++;
if (_concurrency > _tracker._concurrentMax) {
_tracker._concurrentMax = _concurrency;
}
pending = checkForPending();
}
if (pending != null)
{
pending.deliver();
}
return new CallCompletionImpl(currentTime);
}
我正在尝试用 AtomicLong 替换_lastStartTime
:
public CallCompletion startCall()
{
long currentTime;
Pending pending = null;
long lastStartTime = _lastStartTime.get();
currentTime = _clock.currentTimeMillis();
//synchronized (_lock)
//{
if (_lastStartTime.compareAndSet(lastStartTime, currentTime)) {
System.out.println("Inside atomic if -->" + Thread.currentThread().getName());
//_lastStartTime = currentTime;
_tracker.getStatsWithCurrentTime(currentTime);
_sumOfOutstandingStartTimes += currentTime;
_callStartCountTotal++;
_tracker._callStartCount++;
if (_callStartsInLastSecondTracker != null) _callStartsInLastSecondTracker.addCall();
_concurrency++;
if (_concurrency > _tracker._concurrentMax) {
_tracker._concurrentMax = _concurrency;
}
pending = checkForPending();
System.out.println("Leaving atomic if -->" + Thread.currentThread().getName());
}
// }
if (pending != null)
{
pending.deliver();
}
return new CallCompletionImpl(currentTime);
}
compareAndSet
然而,尽管大多数线程是按顺序进入和退出块的,但还是有一些线程搞砸了:
Inside atomic if -->pool-1-thread-3
Inside atomic if -->pool-1-thread-2
Leaving atomic if -->pool-1-thread-2
Leaving atomic if -->pool-1-thread-3
不确定我的逻辑是否正确同步执行或我做错了什么。任何帮助将不胜感激。