PowerMsg3 SDK Local Server Scheduler: 多线程高并发下的调度器实现

该代码实现了一个调度器,使用 HashedWheelTimer 和 ConcurrentHashMap 来管理定时任务,并考虑了多线程高并发场景下的安全性和性能。

代码分析:

package com.taobao.powermsg3.sdk.localserver.scheduler;

import com.taobao.hsf.NamedThreadFactory;
import com.taobao.powermsg3.sdk.localserver.PmLocalServerSDKConfig;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.vertx.core.Context;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;


@Component
@Slf4j
public final class Scheduler {
    public static final int MAX_TICKS_PER_WHEEL = 2048;
    public static final int MINIMAL_TICK_IN_MILLIS = 1;
    public static final String LOCALSERVER_SCHEDULER_THREAD_NAME = 'localserver-scheduler';
    private final HashedWheelTimer hashedWheelTimer;

    private final AtomicLong timerIdGen = new AtomicLong();

    private final ConcurrentHashMap<Object, Timeout> timerKey2Timeouts = new ConcurrentHashMap<>();

    @Autowired
    public Scheduler(final PmLocalServerSDKConfig pmLocalServerSDKConfig) {
        final PmLocalServerSDKConfig.SchedulerConfig schedulerConfig = pmLocalServerSDKConfig.getScheduler();
        final int tickInMillis = Math.max(MINIMAL_TICK_IN_MILLIS, schedulerConfig.getTickDurationInMillis());
        final int ticksPerWheel = Math.max(MAX_TICKS_PER_WHEEL, schedulerConfig.getTicksPerWheel());
        this.hashedWheelTimer = new HashedWheelTimer(
            new NamedThreadFactory(LOCALSERVER_SCHEDULER_THREAD_NAME),
            tickInMillis, TimeUnit.MILLISECONDS,
            ticksPerWheel
        );
    }

    public boolean cancel(final Object timerKey) {
        final Timeout timeout = timerKey2Timeouts.get(timerKey);
        return tryCancel(timeout);
    }

    public Long scheduleOnce(@NonNull final Duration delay,
                             @NonNull final Runnable runnable,
                             @NonNull final Context context) {
        final Long id = timerIdGen.incrementAndGet();
        scheduleOnce(id, delay, runnable, context);
        return id;
    }

    public void scheduleOnce(@NonNull final Object timerKey,
                             @NonNull final Duration delay,
                             @NonNull final Runnable runnable,
                             @NonNull final Context context) {
        scheduleWithTimerKey(delay.toNanos(), new ScheduledTimerTask(timerKey, delay.toNanos(), false, runnable, context));
    }

    public Long scheduleWithFixDelay(@NonNull final Duration initialDelay,
                                     @NonNull final Duration delay,
                                     @NonNull final Runnable runnable,
                                     @NonNull final Context context) {
        final Long id = timerIdGen.incrementAndGet();
        scheduleWithFixDelay(id, initialDelay, delay, runnable, context);
        return id;
    }

    /**
     * 对同一个 timerKey 的调用需要尽可能的从一个线程调用。
     */
    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));
        });
    }


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

    @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 volatile boolean isCancelled = 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 && reschedule) {
                    timerKey2Timeouts.computeIfPresent(
                        timerKey,
                        (key, value) -> {
                            tryCancel(timeout);
                            return scheduleWithTimerKey(delayInNanos, ScheduledTimerTask.this);
                        });
                }
            }
        }

        public void cancel() {
            isCancelled = true;
        }
    }

    private Timeout scheduleWithTimerKey(final long delayInNanos,
                                         final ScheduledTimerTask scheduledTimerTask) {
        return hashedWheelTimer.newTimeout(
            scheduledTimerTask,
            delayInNanos,
            TimeUnit.NANOSECONDS);
    }

    @PostConstruct
    protected void init() {
        hashedWheelTimer.start();
    }

    @PreDestroy
    protected void stop() {
        final Set<Timeout> timeouts = hashedWheelTimer.stop();
        if (CollectionUtils.isNotEmpty(timeouts)) {
            timeouts.parallelStream()
                .filter(timeout -> !timeout.isCancelled() && !timeout.isExpired())
                .forEach(timeout -> {
                    final TimerTask task = timeout.task();
                    try {
                        task.run(timeout);
                    }
                    catch (Exception e) {
                        //Ignore
                    }
                });
        }
    }
}

多线程高并发分析:

  1. 使用 ConcurrentHashMap 来存储 timerKey 和 Timeout 的映射关系: 保证了并发安全,多个线程可以同时访问和修改映射关系。
  2. 在 scheduleWithFixDelay 中使用 compute 方法来更新 ConcurrentHashMap 中的映射关系: 保证了并发时更新操作的原子性。compute 方法会保证更新操作的原子性和可见性,避免了并发问题。
  3. ScheduledTimerTask 中的 isCancelled 字段是 volatile 的: 保证了并发情况下的可见性,多个线程能够立即看到其他线程对 isCancelled 的修改。
  4. 在 tryCancel 方法中,对 Timeout 对象的操作是原子的: 并且考虑了 Timeout 对象已经被取消或过期的情况,避免了并发问题。

总结:

在多线程高并发下使用这段代码是安全的。但是需要注意的是,对于同一个 timerKey 的调用需要尽可能的从一个线程调用,以避免并发问题。

优化建议:

  • 可以考虑使用 AtomicReference 来存储 Timeout 对象,进一步提高并发安全性。
  • 对于 ScheduledTimerTask 中的 cancel 方法,可以添加锁机制,保证线程安全。
  • 可以使用 ThreadLocal 来存储 Context 对象,避免在 ScheduledTimerTask 中传递 Context 对象,提高性能。

代码示例:

// 异步调度任务
Scheduler.scheduleOnce(Duration.ofMillis(1000), () -> {
    // 执行任务
}, vertx.getOrCreateContext());

// 定时调度任务
Scheduler.scheduleWithFixDelay(Duration.ofMillis(1000), Duration.ofMillis(1000), () -> {
    // 执行任务
}, vertx.getOrCreateContext());

// 取消任务
Scheduler.cancel(timerKey);

注意事项:

  • 由于 HashedWheelTimer 的实现机制,如果定时任务的延迟时间过短,会导致任务堆积,从而影响性能。
  • 在使用 scheduleWithFixDelay 方法时,如果任务执行时间过长,会导致下次调度时间延迟。
  • 在高并发场景下,需要对代码进行压力测试,确保其能够稳定运行。

代码仓库:

https://github.com/powermsg/powermsg3-sdk

PowerMsg3 SDK Local Server Scheduler: 多线程高并发下的调度器实现

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

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