PowerMsg3 SDK Local Server Scheduler: Thread-Safe and Efficient Task Scheduling
PowerMsg3 SDK Local Server Scheduler: Thread-Safe and Efficient Task Scheduling
The PowerMsg3 SDK Local Server utilizes a dedicated Scheduler component for managing and executing tasks. This component is crucial for handling various time-sensitive operations within the server. This article delves into the design and implementation of the Scheduler, focusing on its thread safety, particularly the scheduleWithFixDelay method, and discussing how it handles concurrent task scheduling in a robust and efficient manner.
Code Analysis: scheduleWithFixDelay and Thread Safety
The scheduleWithFixDelay method is responsible for scheduling tasks that need to be executed repeatedly with a fixed delay between each execution. Let's break down the code to analyze its thread safety:
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;
}
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
}
});
}
}
}
-
Thread-Safe Data Structures: The core data structure
timerKey2Timeoutsis aConcurrentHashMap, designed for concurrent read and write operations. This ensures that multiple threads can access and modify this map safely without causing race conditions. -
Atomic Operations: The
scheduleWithFixDelaymethod usestimerKey2Timeouts.compute. This method is an atomic operation that guarantees thread safety. It essentially performs a read, update, and write operation within a single, uninterrupted step. TheConcurrentHashMapimplementation uses techniques like CAS (Compare-and-Swap) operations and internal locks to achieve this atomicity. -
Vert.x Event Loop: The
ScheduledTimerTaskutilizes thecontext.runOnContextmethod. This ensures that the task'srunnableis executed on the Vert.x event loop thread, which is responsible for handling asynchronous operations and preventing concurrency issues. In essence, the task is placed onto the Vert.x event loop's queue and executed when it's the event loop's turn to process it, thereby eliminating the potential for direct concurrent execution between threads.
Conclusion
The PowerMsg3 SDK Local Server Scheduler is designed to handle concurrent task scheduling safely and efficiently. The use of thread-safe data structures like ConcurrentHashMap, atomic operations, and the Vert.x event loop ensures that the scheduleWithFixDelay method and the scheduler as a whole operate without introducing concurrency issues in multi-threaded, high-concurrency scenarios. This approach provides a robust and reliable foundation for managing tasks within the local server, contributing to its overall stability and performance.
原文地址: https://www.cveoy.top/t/topic/lIeG 著作权归作者所有。请勿转载和采集!