PowerMsg3 Local Server SDK 定时任务调度器优化:并发安全问题解决

PowerMsg3 Local Server SDK 提供了一个基于 HashedWheelTimer 的定时任务调度器,用于在应用程序中执行定时任务。然而,在高并发场景下,scheduleWithFixDelay 方法存在并发问题,可能导致数据错乱或覆盖。本文将深入分析该问题,并给出解决方案。

问题分析

scheduleWithFixDelay 方法使用 ConcurrentHashMap 存储定时器的 key 和对应的 Timeout,ConcurrentHashMap 只能保证多线程读写时的线程安全,无法保证多线程操作的原子性。

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

在高并发情况下,多个线程可能同时调用 scheduleWithFixDelay 方法并传入相同的 timerKey。由于 compute 方法无法保证原子性,可能会出现多个线程同时写入同一个 key,导致数据错乱或覆盖的情况。

解决方案

为了解决并发问题,可以使用 putIfAbsent 方法替换 compute 方法,确保只有一个线程写入同一个 key。修改后的代码如下:

public void scheduleWithFixDelay(@NonNull final Object timerKey,
                                 @NonNull final Duration initialDelay,
                                 @NonNull final Duration delay,
                                 @NonNull final Runnable runnable,
                                 @NonNull final Context context) {
    final ScheduledTimerTask scheduledTimerTask = new ScheduledTimerTask(timerKey, delay.toNanos(), true, runnable, context);
    final Timeout timeout = scheduleWithTimerKey(initialDelay.toNanos(), scheduledTimerTask);
    final Timeout oldTimeout = timerKey2Timeouts.putIfAbsent(timerKey, timeout);
    if (oldTimeout != null) {
        tryCancel(oldTimeout);
        timerKey2Timeouts.put(timerKey, scheduleWithTimerKey(initialDelay.toNanos(), scheduledTimerTask));
    }
}

putIfAbsent 方法在 timerKey2Timeouts 中查找 timerKey,如果存在,则返回该 key 对应的 Timeout 对象,否则将新的 Timeout 对象插入到 timerKey2Timeouts 中,并返回 null。通过这种方式,可以确保只有一个线程写入同一个 key,避免并发问题。

总结

通过使用 putIfAbsent 方法替换 compute 方法,可以有效解决 PowerMsg3 Local Server SDK 定时任务调度器中 scheduleWithFixDelay 方法的并发安全问题。在高并发场景下,建议使用此优化方案,以确保代码的稳定性和可靠性。

PowerMsg3 Local Server SDK 定时任务调度器优化:并发安全问题解决

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

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