PowerMsg3 LocalServer Scheduler 多线程安全定时任务调度

PowerMsg3 LocalServer Scheduler 提供了线程安全的多线程定时任务调度功能,可以解决高并发场景下同一个 timerKey 可能导致的任务重复执行或取消问题。

原代码存在的问题

在高并发环境下,scheduleWithFixDelay 方法存在并发问题,可能导致同一个 timerKey 对应的任务被重复执行或者被取消。

  1. 使用 ConcurrentHashMap 的 compute 方法可能导致新的任务覆盖旧的任务:compute 方法会将旧的任务替换成新的任务,而不是将新的任务添加到旧的任务列表中。

  2. 多个线程同时操作同一个 timerKey 可能导致任务被取消或者重复执行:当多个线程同时调用 scheduleWithFixDelay 方法时,可能会同时对同一个 timerKey 进行操作,导致其中一个线程的操作被覆盖。

解决方法

为了解决这个问题,可以使用 ConcurrentHashMap 的 computeIfAbsent 方法来替换 compute 方法,并将同一个 timerKey 对应的多个任务存储在一个 ScheduledTimerTaskList 中。

修改后的 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.computeIfAbsent(timerKey, key -> new ScheduledTimerTaskList())
                     .add(new ScheduledTimerTask(initialDelay.toNanos(), delay.toNanos(), true, runnable, context));
}

ScheduledTimerTaskList 类:

@Data
private class ScheduledTimerTaskList {
    private final List<ScheduledTimerTask> tasks = new ArrayList<>();

    public void add(ScheduledTimerTask task) {
        tasks.add(task);
    }

    public void remove(ScheduledTimerTask task) {
        tasks.remove(task);
    }

    public boolean isEmpty() {
        return tasks.isEmpty();
    }
}

修改后的代码可以保证线程安全,同时也能够正确地处理同一个 timerKey 对应的多个任务。

总结

PowerMsg3 LocalServer Scheduler 通过使用 ConcurrentHashMap 的 computeIfAbsent 方法和 ScheduledTimerTaskList 类,解决了高并发环境下定时任务调度可能出现的并发问题,确保了任务的正确执行。

PowerMsg3 LocalServer Scheduler: 多线程安全定时任务调度

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

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