Skip to content

Commit

Permalink
restored volatile, cache value before comparand
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaronontheweb committed Apr 26, 2024
1 parent 38f5775 commit f52379b
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/core/Akka/Actor/Scheduler/HashedWheelTimerScheduler.cs
Expand Up @@ -114,7 +114,7 @@ public HashedWheelTimerScheduler(Config scheduler, ILoggingAdapter log) : base(s
/// <summary>
/// 0 - init, 1 - started, 2 - shutdown
/// </summary>
private int _workerState = WORKER_STATE_INIT;
private volatile int _workerState = WORKER_STATE_INIT;

private static Bucket[] CreateWheel(int ticksPerWheel, ILoggingAdapter log)
{
Expand Down Expand Up @@ -147,25 +147,27 @@ private static int NormalizeTicksPerWheel(int ticksPerWheel)

private void Start()
{
if (_workerState == WORKER_STATE_STARTED)
// only read the worker state once so it can't be a moving target for else-branch
var workerStateRead = _workerState;
if (workerStateRead == WORKER_STATE_STARTED)
{
// do nothing
}
else if (_workerState == WORKER_STATE_INIT)
else if (workerStateRead == WORKER_STATE_INIT)
{
if (Interlocked.CompareExchange(ref _workerState, WORKER_STATE_STARTED, WORKER_STATE_INIT) == WORKER_STATE_INIT)
{
_timer ??= new PeriodicTimer(_timerDuration);
Task.Run(() => RunAsync(_cts.Token)); // start the clock
Task.Run(() => RunAsync(_cts.Token).ConfigureAwait(false)); // start the clock
}
}
else if (_workerState == WORKER_STATE_SHUTDOWN)
else if (workerStateRead == WORKER_STATE_SHUTDOWN)
{
throw new SchedulerException("cannot enqueue after timer shutdown");
}
else
{
throw new InvalidOperationException($"Worker in invalid state: {_workerState}");
throw new InvalidOperationException($"Worker in invalid state: {workerStateRead}");
}

if(_startTime == 0)
Expand Down

0 comments on commit f52379b

Please sign in to comment.