21
21
22
22
import java .util .Comparator ;
23
23
import java .util .TreeSet ;
24
+ import java .util .concurrent .locks .Lock ;
25
+ import java .util .concurrent .locks .ReentrantLock ;
24
26
25
27
/**
26
28
* Created by [email protected] on 2017/3/31.
@@ -44,6 +46,7 @@ public int compare(TopUtil.Entry<Id, Long> o1,
44
46
};
45
47
private final TopUtil .Order order ;
46
48
private long lastRolledStamp = -1l ;
49
+ private final Lock lock = new ReentrantLock ();
47
50
48
51
AbstractTopMetric (Registry registry , Id id , int maxNumber , TopUtil .Order order ) {
49
52
this .maxNumber = maxNumber ;
@@ -57,32 +60,35 @@ protected void pushAsync(Long value, Id timerId) {
57
60
TopUtil .executor .execute (new Runnable () {
58
61
@ Override
59
62
public void run () {
60
- pushSafe (set , entry );
63
+ lock .lock ();
64
+ try {
65
+ pushSafe (set , entry );
66
+ } finally {
67
+ lock .unlock ();
68
+ }
61
69
}
62
70
});
63
71
}
64
72
65
73
private void pushSafe (TreeSet <TopUtil .Entry <Id , Long >> set , TopUtil .Entry <Id , Long > e ) {
66
- synchronized (set ) {
67
- if (!set .isEmpty ()) {
68
- boolean replaceable = false ;
69
- TopUtil .Entry <Id , Long > boundaryTarget = null ;
70
- if (order == TopUtil .Order .DESC ) {
71
- boundaryTarget = set .first ();
72
- replaceable = boundaryTarget .getValue () < e .getValue ();
73
- } else {
74
- boundaryTarget = set .last ();
75
- replaceable = boundaryTarget .getValue () > e .getValue ();
76
- }
77
- if (replaceable & set .size () >= maxNumber ) {
78
- remove (set , boundaryTarget );
79
- }
80
- if (!replaceable & set .size () >= maxNumber ) {
81
- return ;//不add
82
- }
74
+ if (!set .isEmpty ()) {
75
+ boolean replaceable = false ;
76
+ TopUtil .Entry <Id , Long > boundaryTarget = null ;
77
+ if (order == TopUtil .Order .DESC ) {
78
+ boundaryTarget = set .first ();
79
+ replaceable = boundaryTarget .getValue () < e .getValue ();
80
+ } else {
81
+ boundaryTarget = set .last ();
82
+ replaceable = boundaryTarget .getValue () > e .getValue ();
83
+ }
84
+ if (replaceable & set .size () >= maxNumber ) {
85
+ remove (set , boundaryTarget );
86
+ }
87
+ if (!replaceable & set .size () >= maxNumber ) {
88
+ return ;//不add
83
89
}
84
- add (set , e );
85
90
}
91
+ add (set , e );
86
92
}
87
93
88
94
private void remove (TreeSet <TopUtil .Entry <Id , Long >> set , TopUtil .Entry <Id , Long > boundaryTarget ) {
0 commit comments