PowerMsg3 LocalServer SDK 定时任务调度器并发问题分析与解决方案

在多线程高并发场景下使用 PowerMsg3 LocalServer SDK 的 Scheduler 类进行定时任务调度时,scheduleWithFixDelay 方法存在潜在的并发问题。本文将深入分析该问题,并提供解决方案。

问题分析

scheduleWithFixDelay 方法的主要逻辑是:

  1. 从 timerKey2Timeouts 中移除与 timerKey 对应的 Timeout 对象。
  2. 创建新的 ScheduledTimerTask 对象,并将其与 timerKey 关联,添加到 timerKey2Timeouts 中。

其中,timerKey2Timeouts 是一个 ConcurrentHashMap 对象。然而,在移除和添加操作中,没有使用原子操作或锁机制来保证线程安全,从而导致潜在的并发问题。

具体来说,存在以下两种情况可能导致问题:

  1. 多个线程同时移除同一 timerKey 对应的 Timeout,然后添加新的 ScheduledTimerTask。 这会导致最后添加的 ScheduledTimerTask 覆盖掉之前添加的 ScheduledTimerTask,导致定时任务被取消。

  2. 多个线程同时将新的 ScheduledTimerTask 添加到 timerKey2Timeouts 中。 这会导致其中一些 ScheduledTimerTask 被覆盖掉,同样导致定时任务被取消。

解决方案

为了解决上述并发问题,需要保证对 timerKey2Timeouts 的修改操作的线程安全性。可以使用 ConcurrentHashMap.compute 方法来替代 ConcurrentHashMap.put 方法,从而保证线程安全。

修改后的 scheduleWithFixDelay 方法代码如下:

public void scheduleWithFixDelay(@NonNull final Object timerKey,
                                 @NonNull final Duration initialDelay,
                                 @NonNull final Duration delay,
                                 @NonNull final Runnable runnable,
                                 @NonNull final Context context) {
    timerKey2Timeouts.compute(timerKey, (key, timeout) -> {
        tryCancel(timeout);
        return scheduleWithTimerKey(initialDelay.toNanos(),
            new ScheduledTimerTask(timerKey, delay.toNanos(), true, runnable, context));
    });
}

总结

通过使用 ConcurrentHashMap.compute 方法,可以确保对 timerKey2Timeouts 的修改操作的线程安全性,从而解决 scheduleWithFixDelay 方法的并发问题。在多线程高并发场景下,使用 Scheduler 类进行定时任务调度时,务必注意线程安全问题,并采用合适的解决方案来确保代码的正确性和稳定性。

PowerMsg3 LocalServer SDK 定时任务调度器并发问题分析与解决方案

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

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