PowerMsg3 SDK Local Server Scheduler 并发问题及解决方案

经过分析,scheduleWithFixDelay 方法可能存在并发问题。

在多线程环境下,如果两个线程同时调用 scheduleWithFixDelay 方法,会同时执行 timerKey2Timeouts.computeIfAbsent 方法,可能会导致同一个 timerKey 对应的 Timeout 对象被创建多次,从而导致同一个定时任务被触发多次。

解决方案

使用 ConcurrentHashMap 的 putIfAbsent 方法代替 computeIfAbsent 方法,保证同一个 timerKey 只会被创建一次。

修改后的代码

public void scheduleWithFixDelay(@NonNull final Object timerKey,
                                 @NonNull final Duration initialDelay,
                                 @NonNull final Duration delay,
                                 @NonNull final Runnable runnable,
                                 @NonNull final Context context) {
    final Timeout timeout = hashedWheelTimer.newTimeout(
        new ScheduledTimerTask(timerKey, delay.toNanos(), true, runnable, context),
        initialDelay.toNanos(),
        TimeUnit.NANOSECONDS);
    timerKey2Timeouts.putIfAbsent(timerKey, timeout);
}

通过以上修改,scheduleWithFixDelay 方法在多线程环境下能够正常工作,避免了并发问题。

PowerMsg3 SDK Local Server Scheduler 并发问题及解决方案

原文地址: https://www.cveoy.top/t/topic/lIfk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录