Does AtomicLong's compareAndSet ensure threadsafety

85 views Asked by At

This is in continuation to my previous question - Refactoring synchronization blocks keeping ordering of execution intact

I have a synchronized block in one the functions which I want to do away with, having something else to reduce contention and improve performance.

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);
}

I am trying to replace with an AtomicLong for _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);
}

However, although most threads enter and exit the compareAndSet block sequentially, there are a few threads which gets messed up:

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

Not sure if my logic is correctly synchronising the execution or where I am doing wrong. Any help will be appreciated.

0

There are 0 answers