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

    public void scheduleWithFixDelay(@NonNull final Object timerKey,
                                     @NonNull final Duration initialDelay,
                                     @NonNull final Duration delay,
                                     @NonNull final Runnable runnable,
                                     @NonNull final Context context) {
        tryCancel(timerKey2Timeouts.remove(timerKey));
        timerKey2Timeouts.computeIfAbsent(timerKey, (key) ->
            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;
        }
        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;

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

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


Analysis of scheduleWithFixDelay and Potential Issues:

While the code appears to be generally sound, several key aspects need careful consideration to ensure its reliability in a high-concurrency environment. Here's a breakdown:

  1. Thread Safety: The ConcurrentHashMap used for timerKey2Timeouts is inherently thread-safe. However, it's vital to ensure that any custom logic within your tasks doesn't introduce race conditions or other concurrency issues.

  2. Delayed Time Accuracy: Using Duration offers nanosecond precision, but the HashedWheelTimer's newTimeout method has millisecond-level accuracy. This mismatch can lead to slight inaccuracies in delay execution. For critical applications, consider alternative timers offering higher precision if needed.

  3. Exception Handling: The current code logs errors encountered during task execution but doesn't have robust error handling. Consider strategies like retry mechanisms, error queuing, or notification systems to manage exceptions effectively.

  4. Task Correctness in Concurrency: High concurrency can introduce scheduling challenges. While the Scheduler appears to be well-designed, ensure that your task logic remains correct even if execution order changes due to thread scheduling.

  5. Task Cancellation: The cancel method handles cancellation but might not be entirely bulletproof. For instance, a task might already be executing when cancellation is requested. Consider adding logic to interrupt or gracefully terminate such tasks.

Regarding scheduleWithFixDelay: The issue is not with the method itself, but with the general challenges of implementing fixed-delay scheduling in a multi-threaded environment. The potential for slight delay inaccuracies should be considered, as discussed above. The method's simplicity is generally a strength, but ensure it aligns with your application's precise timing requirements.

Best Practices for Reliable Scheduling in High-Concurrency:

  • Thread-Safe Task Logic: Prioritize thread-safe code in your tasks. Use synchronization or immutable objects where necessary.

  • Precise Timing Requirements: Evaluate your application's need for precision. If nanosecond accuracy is crucial, investigate timers that offer it. Consider using java.time.Instant and Duration for managing delays internally.

  • Robust Exception Handling: Design a comprehensive exception handling strategy. This could involve logging, retry attempts, queuing errors for later processing, or notifying external systems.

  • Task Cancellation: Implement a clear and reliable mechanism for canceling tasks. Ideally, the cancellation process should be non-blocking and gracefully stop the task even if it's already executing.

  • Testing: Thoroughly test your scheduler's behavior under heavy load. Use tools like JMeter to simulate high concurrency and analyze performance and accuracy.

PowerMsg3 LocalServer Scheduler: Reliable Task Scheduling for High-Concurrency Environments

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

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