1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.handler.traffic;
17
18 import io.netty5.handler.traffic.GlobalChannelTrafficShapingHandler.PerChannel;
19 import io.netty5.util.concurrent.EventExecutorGroup;
20
21 import java.util.concurrent.TimeUnit;
22
23 import static io.netty5.util.internal.ObjectUtil.checkNotNullWithIAE;
24
25
26
27
28
29
30
31 public class GlobalChannelTrafficCounter extends TrafficCounter {
32
33
34
35
36
37
38 public GlobalChannelTrafficCounter(GlobalChannelTrafficShapingHandler trafficShapingHandler,
39 EventExecutorGroup executor, String name, long checkInterval) {
40 super(trafficShapingHandler, executor, name, checkInterval);
41 checkNotNullWithIAE(executor, "executor");
42 }
43
44
45
46
47
48 private static class MixedTrafficMonitoringTask implements Runnable {
49
50
51
52 private final GlobalChannelTrafficShapingHandler trafficShapingHandler1;
53
54
55
56
57 private final TrafficCounter counter;
58
59
60
61
62
63 MixedTrafficMonitoringTask(
64 GlobalChannelTrafficShapingHandler trafficShapingHandler,
65 TrafficCounter counter) {
66 trafficShapingHandler1 = trafficShapingHandler;
67 this.counter = counter;
68 }
69
70 @Override
71 public void run() {
72 if (!counter.monitorActive) {
73 return;
74 }
75 long newLastTime = milliSecondFromNano();
76 counter.resetAccounting(newLastTime);
77 for (PerChannel perChannel : trafficShapingHandler1.channelQueues.values()) {
78 perChannel.channelTrafficCounter.resetAccounting(newLastTime);
79 }
80 trafficShapingHandler1.doAccounting(counter);
81 }
82 }
83
84
85
86
87 @Override
88 public synchronized void start() {
89 if (monitorActive) {
90 return;
91 }
92 lastTime.set(milliSecondFromNano());
93 long localCheckInterval = checkInterval.get();
94 if (localCheckInterval > 0) {
95 monitorActive = true;
96 monitor = new MixedTrafficMonitoringTask((GlobalChannelTrafficShapingHandler) trafficShapingHandler, this);
97 scheduledFuture =
98 executor.scheduleAtFixedRate(monitor, 0, localCheckInterval, TimeUnit.MILLISECONDS);
99 }
100 }
101
102
103
104
105 @Override
106 public synchronized void stop() {
107 if (!monitorActive) {
108 return;
109 }
110 monitorActive = false;
111 resetAccounting(milliSecondFromNano());
112 trafficShapingHandler.doAccounting(this);
113 if (scheduledFuture != null) {
114 scheduledFuture.cancel();
115 }
116 }
117
118 @Override
119 public void resetCumulativeTime() {
120 for (PerChannel perChannel :
121 ((GlobalChannelTrafficShapingHandler) trafficShapingHandler).channelQueues.values()) {
122 perChannel.channelTrafficCounter.resetCumulativeTime();
123 }
124 super.resetCumulativeTime();
125 }
126
127 }