PowerMsg3 Local Server Scheduler: Concurrent Issue in scheduleWithFixDelay and Solution
The provided code snippet for the Scheduler class in PowerMsg3 Local Server SDK contains a potential concurrency issue in the scheduleWithFixDelay method. While the use of ConcurrentHashMap for timerKey2Timeouts provides thread safety, the operations within this method, particularly computeIfAbsent, are not atomic, leading to potential problems in concurrent scenarios.
Issue:
When two or more threads concurrently invoke scheduleWithFixDelay using the same timerKey, the computeIfAbsent method can create multiple ScheduledTimerTask instances, attempting to add them to the timerKey2Timeouts map simultaneously. This can result in one thread's task being overwritten by another, leading to unexpected behavior and potential task cancellation.
Solution:
The solution is to replace computeIfAbsent with putIfAbsent in the scheduleWithFixDelay method. This ensures atomic operations, guaranteeing that only one ScheduledTimerTask is associated with a given timerKey at a time. Here's the modified code snippet:
public void scheduleWithFixDelay(@NonNull final Object timerKey,
@NonNull final Duration initialDelay,
@NonNull final Duration delay,
@NonNull final Runnable runnable,
@NonNull final Context context) {
ScheduledTimerTask scheduledTimerTask = new ScheduledTimerTask(timerKey, delay.toNanos(), true, runnable, context);
Timeout timeout = hashedWheelTimer.newTimeout(scheduledTimerTask, initialDelay.toNanos(), TimeUnit.NANOSECONDS);
Timeout prevTimeout = timerKey2Timeouts.putIfAbsent(timerKey, timeout);
if (prevTimeout != null) {
tryCancel(timeout);
}
}
By using putIfAbsent, we ensure that if a timeout already exists for the given timerKey, the new timeout will not be added, preventing the overwriting issue and ensuring correct concurrent behavior.
This modification resolves the potential concurrency issue in scheduleWithFixDelay by guaranteeing atomic operations for adding scheduled tasks to the timerKey2Timeouts map.
原文地址: https://www.cveoy.top/t/topic/lIfm 著作权归作者所有。请勿转载和采集!