1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
| import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong;
public class TimingWheelTimer { private static final int SECOND_WHEEL_SIZE = 512; private static final int MS_WHEEL_SIZE = 1000; private static final int MS_PER_SLOT = 1;
private final List<Set<TimerTask>> secondWheel; private final List<Set<TimerTask>> msWheel;
private final Set<Long> canceledTasks;
private int currentSecondSlot; private int currentMsSlot; private volatile long currentTime; private volatile boolean running;
private final Thread workerThread;
private final AtomicLong idGenerator;
public TimingWheelTimer() { this.secondWheel = new ArrayList<>(SECOND_WHEEL_SIZE); this.msWheel = new ArrayList<>(MS_WHEEL_SIZE);
for (int i = 0; i < SECOND_WHEEL_SIZE; i++) { secondWheel.add(Collections.synchronizedSet(new HashSet<>())); } for (int i = 0; i < MS_WHEEL_SIZE; i++) { msWheel.add(Collections.synchronizedSet(new HashSet<>())); }
this.canceledTasks = Collections.synchronizedSet(new HashSet<>()); this.currentSecondSlot = 0; this.currentMsSlot = 0; this.currentTime = System.currentTimeMillis(); this.running = true; this.idGenerator = new AtomicLong(1);
this.workerThread = new Thread(this::run); this.workerThread.setDaemon(true); this.workerThread.start(); }
private static class TimerTask { final long id; final long expireTime; final long interval; final Runnable task; final boolean isRepeating;
TimerTask(long id, long expireTime, long interval, Runnable task, boolean isRepeating) { this.id = id; this.expireTime = expireTime; this.interval = interval; this.task = task; this.isRepeating = isRepeating; } }
private int[] calculateSlots(long timestamp) { long delta = timestamp - currentTime;
if (delta < MS_WHEEL_SIZE * MS_PER_SLOT) { int msSlot = (currentMsSlot + (int)(delta / MS_PER_SLOT)) % MS_WHEEL_SIZE; return new int[]{-1, msSlot}; } else { int secondDelta = (int)(delta / 1000); int secondSlot = (currentSecondSlot + secondDelta) % SECOND_WHEEL_SIZE; return new int[]{secondSlot, -1}; } }
public long addTask(long delayMs, Runnable task) { long id = idGenerator.getAndIncrement(); long expireTime = currentTime + delayMs; TimerTask timerTask = new TimerTask(id, expireTime, 0, task, false);
int[] slots = calculateSlots(expireTime); if (slots[0] == -1) { msWheel.get(slots[1]).add(timerTask); } else { secondWheel.get(slots[0]).add(timerTask); }
return id; }
public long addRepeatingTask(long delayMs, Runnable task, long intervalMs) { long id = idGenerator.getAndIncrement(); long expireTime = currentTime + delayMs; TimerTask timerTask = new TimerTask(id, expireTime, intervalMs, task, true);
int[] slots = calculateSlots(expireTime); if (slots[0] == -1) { msWheel.get(slots[1]).add(timerTask); } else { secondWheel.get(slots[0]).add(timerTask); }
return id; }
public boolean cancelTask(long taskId) { return canceledTasks.add(taskId); }
private void migrateSecondWheelTasks() { Set<TimerTask> tasks = secondWheel.get(currentSecondSlot); if (tasks.isEmpty()) { return; }
Set<TimerTask> toRemove = new HashSet<>(); Set<TimerTask> toAddMsWheel = new HashSet<>();
synchronized (tasks) { Iterator<TimerTask> iterator = tasks.iterator(); while (iterator.hasNext()) { TimerTask task = iterator.next(); if (canceledTasks.contains(task.id)) { toRemove.add(task); iterator.remove(); continue; }
long remaining = task.expireTime - currentTime; if (remaining <= 0) { executeTask(task); toRemove.add(task); iterator.remove(); } else if (remaining < MS_WHEEL_SIZE * MS_PER_SLOT) { int msSlot = (currentMsSlot + (int)(remaining / MS_PER_SLOT)) % MS_WHEEL_SIZE; toAddMsWheel.add(task); toRemove.add(task); iterator.remove(); } } }
for (TimerTask task : toAddMsWheel) { long remaining = task.expireTime - currentTime; int msSlot = (currentMsSlot + (int)(remaining / MS_PER_SLOT)) % MS_WHEEL_SIZE; msWheel.get(msSlot).add(task); }
for (TimerTask task : toRemove) { canceledTasks.remove(task.id); } }
private void executeTask(TimerTask task) { if (canceledTasks.contains(task.id)) { canceledTasks.remove(task.id); return; }
try { task.task.run(); } catch (Exception e) { e.printStackTrace(); }
if (task.isRepeating && !canceledTasks.contains(task.id)) { long newExpireTime = currentTime + task.interval; TimerTask newTask = new TimerTask(task.id, newExpireTime, task.interval, task.task, true);
int[] slots = calculateSlots(newExpireTime); if (slots[0] == -1) { msWheel.get(slots[1]).add(newTask); } else { secondWheel.get(slots[0]).add(newTask); } } else { canceledTasks.remove(task.id); } }
private void run() { long lastTickTime = System.currentTimeMillis();
while (running) { try { long currentTickTime = System.currentTimeMillis(); long elapsed = currentTickTime - lastTickTime;
if (elapsed > 0) { currentTime = currentTickTime;
int ticks = Math.min((int)elapsed, MS_WHEEL_SIZE); for (int i = 0; i < ticks; i++) { advanceMsWheel(); }
lastTickTime = currentTickTime; }
Thread.sleep(1);
} catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } catch (Exception e) { e.printStackTrace(); } } }
private void advanceMsWheel() { Set<TimerTask> tasks = msWheel.get(currentMsSlot); if (!tasks.isEmpty()) { Set<TimerTask> toExecute = new HashSet<>(); Set<TimerTask> toRemove = new HashSet<>();
synchronized (tasks) { Iterator<TimerTask> iterator = tasks.iterator(); while (iterator.hasNext()) { TimerTask task = iterator.next(); if (canceledTasks.contains(task.id)) { toRemove.add(task); iterator.remove(); } else if (task.expireTime <= currentTime) { toExecute.add(task); toRemove.add(task); iterator.remove(); } } }
for (TimerTask task : toExecute) { executeTask(task); }
for (TimerTask task : toRemove) { canceledTasks.remove(task.id); } }
currentMsSlot = (currentMsSlot + 1) % MS_WHEEL_SIZE;
if (currentMsSlot == 0) { advanceSecondWheel(); } }
private void advanceSecondWheel() { migrateSecondWheelTasks();
currentSecondSlot = (currentSecondSlot + 1) % SECOND_WHEEL_SIZE; }
public void stop() { running = false; workerThread.interrupt(); }
public void printStats() { int secondWheelCount = secondWheel.stream().mapToInt(Set::size).sum(); int msWheelCount = msWheel.stream().mapToInt(Set::size).sum(); int canceledCount = canceledTasks.size();
System.out.printf("时间轮统计: 秒级轮=%d, 毫秒级轮=%d, 取消任务=%d, 总任务=%d%n", secondWheelCount, msWheelCount, canceledCount, secondWheelCount + msWheelCount + canceledCount); }
public static void main(String[] args) throws Exception { TimingWheelTimer timer = new TimingWheelTimer();
System.out.println("开始时间:" + new Date());
long oneTimeTaskId = timer.addTask(6000, () -> System.out.println("[" + new Date() + "] 执行一次性任务") ); System.out.println("添加一次性任务, ID: " + oneTimeTaskId);
long repeatingTaskId = timer.addRepeatingTask(1000, () -> System.out.println("[" + new Date() + "] 执行重复任务"), 2000 ); System.out.println("添加重复任务, ID: " + repeatingTaskId);
long preciseTaskId = timer.addTask(1500, () -> System.out.println("[" + new Date() + "] 执行精确到毫秒的任务 (1500ms)") ); System.out.println("添加精确毫秒任务, ID: " + preciseTaskId);
long task = timer.addTask(3000, ()-> System.out.println("[" + new Date() + "] 3s后执行"));
Thread.sleep(25000);
System.out.println("取消重复任务: " + repeatingTaskId); timer.cancelTask(repeatingTaskId);
timer.printStats();
timer.stop(); } }
|