fix: 时间轮添加任务线程安全问题

This commit is contained in:
BeauFang 2022-11-05 12:37:26 +08:00
parent 4b2ec7d7a5
commit 25e1ee4d62

View File

@ -72,6 +72,7 @@ public class TimingWheel {
this.wheelSize = wheelSize;
this.interval = tickMs * wheelSize;
this.timerTaskLists = new TimerTaskList[wheelSize];
initTimerTaskList();
//currentTime为tickMs的整数倍 这里做取整操作
this.currentTime = currentTime - (currentTime % tickMs);
this.consumer = consumer;
@ -93,12 +94,7 @@ public class TimingWheel {
long virtualId = expiration / tickMs;
int index = (int) (virtualId % wheelSize);
StaticLog.debug("tickMs: {} ------index: {} ------expiration: {}", tickMs, index, expiration);
TimerTaskList timerTaskList = timerTaskLists[index];
if (null == timerTaskList) {
timerTaskList = new TimerTaskList();
timerTaskLists[index] = timerTaskList;
}
timerTaskList.addTask(timerTask);
if (timerTaskList.setExpiration(virtualId * tickMs)) {
//添加到delayQueue中
@ -140,4 +136,13 @@ public class TimingWheel {
}
return overflowWheel;
}
/**
* 初始 timerTaskLists
*/
private void initTimerTaskList() {
for (int i = 0; i < this.timerTaskLists.length; i++) {
this.timerTaskLists[i] = new TimerTaskList();
}
}
}