PowerMsg3 定时器:使用 HashedWheelTimer 实现高性能调度
PowerMsg3 定时器:使用 HashedWheelTimer 实现高性能调度
PowerMsg3 中使用 HashedWheelTimer 实现了一个高效的定时器,用于调度各种任务。HashedWheelTimer 是一种基于时间轮的定时器,它可以高效地处理大量的定时任务。
定时器代码:
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 {
if (isCancelled) {
return;
}
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
}
});
}
}
}
并发问题分析:
scheduleWithFixDelay 方法存在并发问题,因为多个线程可能同时调用 compute 方法,导致对 timerKey2Timeouts 的修改操作不是原子性的。这可能导致以下问题:
-
多个线程同时调用
compute方法,可能会创建多个定时器任务,造成任务重复执行的问题。 -
多个线程同时调用
compute方法,可能会创建多个定时器任务,占用过多的定时器资源,降低定时器的效率。
解决方案:
为了避免上述问题,我们可以使用 putIfAbsent 方法来避免多线程同时创建定时器任务的问题。以下是修改后的 scheduleWithFixDelay 方法:
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);
if (timerKey2Timeouts.putIfAbsent(timerKey, scheduleWithTimerKey(initialDelay.toNanos(), scheduledTimerTask)) == null) {
return;
}
// 如果已经存在定时器任务,则不进行任何操作
tryCancel(timerKey2Timeouts.get(timerKey));
timerKey2Timeouts.put(timerKey, scheduleWithTimerKey(initialDelay.toNanos(), scheduledTimerTask));
}
总结:
通过使用 putIfAbsent 方法,我们成功地解决了 scheduleWithFixDelay 方法的并发问题,并提高了定时器的效率。
注意:
虽然我们解决了并发问题,但是建议您在使用定时器时,尽量避免对同一个 timerKey 进行重复调用,以保证定时器的高效运行。
原文地址: https://www.cveoy.top/t/topic/lIfC 著作权归作者所有。请勿转载和采集!