17
17
18
18
import java .util .List ;
19
19
import java .util .concurrent .TimeUnit ;
20
- import java .util .concurrent .atomic .AtomicLong ;
21
20
22
21
import com .alibaba .csp .sentinel .log .RecordLog ;
23
22
import com .alibaba .csp .sentinel .slots .statistic .base .LeapArray ;
42
41
*/
43
42
public final class TimeUtil implements Runnable {
44
43
private static final long CHECK_INTERVAL = 3000 ;
44
+ private static final long HITS_LOWER_BOUNDARY = 800 ;
45
+ private static final long HITS_UPPER_BOUNDARY = 1200 ;
45
46
46
47
public static enum STATE {
47
48
IDLE , PREPARE , RUNNING ;
@@ -59,9 +60,12 @@ public LongAdder getReads() {
59
60
private static TimeUtil INSTANCE ;
60
61
61
62
private volatile long currentTimeMillis ;
62
- private AtomicLong lastCheck = new AtomicLong ();
63
+ private volatile STATE state = STATE .IDLE ;
64
+
63
65
private LeapArray <Statistic > statistics ;
64
- private STATE state = STATE .IDLE ;
66
+
67
+ // thread private variables
68
+ private long lastCheck = 0 ;
65
69
66
70
static {
67
71
INSTANCE = new TimeUtil ();
@@ -85,6 +89,7 @@ protected WindowWrap<Statistic> resetWindowTo(WindowWrap<Statistic> windowWrap,
85
89
}
86
90
};
87
91
this .currentTimeMillis = System .currentTimeMillis ();
92
+ this .lastCheck = this .currentTimeMillis ;
88
93
Thread daemon = new Thread (this );
89
94
daemon .setDaemon (true );
90
95
daemon .setName ("sentinel-time-tick-thread" );
@@ -155,24 +160,20 @@ public Tuple2<Long, Long> currentQps(long now) {
155
160
156
161
/**
157
162
* Check and operate the state if necessary.
158
- * It deals concurrency .
163
+ * ATTENTION: It's called in daemon thread .
159
164
*/
160
165
private void check () {
161
166
long now = currentTime (true );
162
- long last = this .lastCheck .get ();
163
167
// every period
164
- if (now - last < CHECK_INTERVAL ) {
165
- return ;
166
- }
167
- // concurrent
168
- if (!this .lastCheck .compareAndSet (last , now )) {
168
+ if (now - this .lastCheck < CHECK_INTERVAL ) {
169
169
return ;
170
170
}
171
+ this .lastCheck = now ;
171
172
Tuple2 <Long , Long > qps = currentQps (now );
172
- if (this .state == STATE .IDLE && qps .r1 > 1200 ) {
173
+ if (this .state == STATE .IDLE && qps .r1 > HITS_UPPER_BOUNDARY ) {
173
174
RecordLog .info ("TimeUtil switches to PREPARE for better performance, reads={}/s, writes={}/s" , qps .r1 , qps .r2 );
174
175
this .state = STATE .PREPARE ;
175
- } else if (this .state == STATE .RUNNING && qps .r1 < 800 ) {
176
+ } else if (this .state == STATE .RUNNING && qps .r1 < HITS_LOWER_BOUNDARY ) {
176
177
RecordLog .info ("TimeUtil switches to IDLE due to not enough load, reads={}/s, writes={}/s" , qps .r1 , qps .r2 );
177
178
this .state = STATE .IDLE ;
178
179
}
0 commit comments