PowerMsg3 Local Server SDK 定时器调度器并发问题解决方案

在使用 PowerMsg3 Local Server SDK 定时器调度器 Scheduler 的 scheduleWithFixDelay 方法时,存在潜在的并发问题。如果多个线程同时调用该方法并传入相同的 timerKey,可能会导致并发冲突。

问题分析

scheduleWithFixDelay 方法使用 ConcurrentHashMap 存储 timerKey 和 Timeout 的映射关系。当多个线程同时调用该方法时,可能会同时调用 compute 方法,导致并发问题。

解决方案

为了解决这个问题,可以使用 ConcurrentHashMap 提供的原子性操作,例如 putIfAbsent 和 computeIfPresent。

推荐使用 compute 方法:

timerKey2Timeouts.compute(timerKey, (key, timeout) -> {
    if (timeout != null && !timeout.isCancelled() && !timeout.isExpired()) {
        // 如果 timeout 存在并且没有被取消或过期,那么直接返回原来的值
        return timeout;
    } else {
        // 否则,创建一个新的 timeout 并返回
        return scheduleWithTimerKey(initialDelay.toNanos(),
            new ScheduledTimerTask(timerKey, delay.toNanos(), true, runnable, context));
    }
});

使用 putIfAbsent 方法的示例:

Timeout existingTimeout = timerKey2Timeouts.putIfAbsent(timerKey, new Timeout(...));

if (existingTimeout != null && !existingTimeout.isCancelled() && !existingTimeout.isExpired()) {
    // 如果存在未取消或过期的 Timeout,则直接返回
    return;
}

// 否则,创建一个新的 Timeout
Timeout newTimeout = scheduleWithTimerKey(initialDelay.toNanos(),
    new ScheduledTimerTask(timerKey, delay.toNanos(), true, runnable, context));

// 更新 Timeout
timerKey2Timeouts.put(timerKey, newTimeout);

通过以上两种方法,可以有效地避免并发问题,并保证每个 timerKey 对应的 Timeout 只有一个。

注意:

  • 使用 compute 方法可以更加简洁地实现,但需要谨慎处理 null 值。
  • 使用 putIfAbsent 方法更加直观,但需要额外的代码来更新 Timeout。

选择哪种方法取决于您的具体需求和编码风格。

PowerMsg3 Local Server SDK 定时器调度器:并发问题解决方案

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

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