PowerMsg3 LocalServer SDK Scheduler: 解决高并发下的定时任务安全问题

PowerMsg3 LocalServer SDK 的 Scheduler 模块,使用 HashedWheelTimer 实现定时任务调度。该模块提供了 scheduleOnce 和 scheduleWithFixDelay 两种方法来执行定时任务。

并发问题分析

在多线程高并发环境下使用 scheduleWithFixDelay 方法存在以下并发问题:

  1. 多个线程同时调用 scheduleWithFixDelay 方法,可能会出现同时创建多个 Timeout 对象,并且只有最后一个被放入 timerKey2Timeouts 中,之前创建的 Timeout 对象可能被覆盖,导致之前的定时任务失效。
  2. 如果一个定时任务在执行过程中被取消,但是还没来得及从 timerKey2Timeouts 中移除,此时又有另外一个线程创建了一个相同 timerKey 的定时任务,那么这个定时任务会被取消,导致之前被取消的定时任务又重新生效了。

解决方案

针对上述两个问题,可以考虑以下解决方案:

  1. 使用 ConcurrentHashMap 的 putIfAbsent 方法来保证线程安全。putIfAbsent 方法只会在 ConcurrentHashMap 中不存在指定 key 时才插入新值,避免多个线程同时插入相同 key 的问题。
  2. 修改 ScheduledTimerTask 中的 isCancelled 字段为 AtomicBoolean 类型,以保证线程安全。AtomicBoolean 是一个线程安全的布尔类型,可以保证多个线程对该变量的操作都是原子性的。
  3. 在调用 tryCancel 方法时,需要判断 timeout 是否为 null,以避免空指针异常。

修改后的代码

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(prevTimeout);
        timerKey2Timeouts.replace(timerKey, timeout);
    }
}

@Data
private class ScheduledTimerTask implements TimerTask {
    private final Object timerKey;
    private final long delayInNanos;
    private final boolean reschedule;
    private final Runnable runnable;
    private final Context context;
    private final AtomicBoolean isCancelled = new AtomicBoolean(false);

    @Override
    public void run(final Timeout timeout) throws Exception {
        try {
            context.runOnContext(e -> runnable.run());
        } catch (Exception e) {
            log.error('Error when trigger task of runnable:[{}]', runnable, e);
        } finally {
            if (!isCancelled.get() && reschedule) {
                timerKey2Timeouts.computeIfPresent(
                    timerKey,
                    (key, value) -> {
                        tryCancel(timeout);
                        return scheduleWithTimerKey(delayInNanos, ScheduledTimerTask.this);
                    });
            }
        }
    }

    public void cancel() {
        isCancelled.set(true);
    }
}

private boolean tryCancel(final Timeout timeout) {
    if (timeout == null || timeout.isCancelled() || timeout.isExpired()) {
        return true;
    }
    return timeout.cancel();
}

总结

通过以上修改,可以有效地解决 scheduleWithFixDelay 方法在高并发环境下的并发问题,保证定时任务的线程安全性和可靠性。在使用 HashedWheelTimer 进行定时任务调度时,需要格外注意并发问题,并采取相应的措施确保代码的正确性和稳定性。

PowerMsg3 LocalServer SDK Scheduler: 解决高并发下的定时任务安全问题

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

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