1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.util;
21
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.concurrent.ConcurrentHashMap;
25 import org.apache.hadoop.conf.Configuration;
26 import org.apache.hadoop.hbase.HConstants;
27 import org.apache.hadoop.hbase.classification.InterfaceAudience;
28
29
30
31
32
33
34
35
36
37
38
39 @InterfaceAudience.Private
40 public class LossyCounting {
41 private long bucketSize;
42 private int currentTerm;
43 private Map<String, Integer> data;
44 private long totalDataCount;
45 private LossyCountingListener listener;
46
47 public interface LossyCountingListener {
48 void sweep(String key);
49 }
50
51 LossyCounting(double errorRate) {
52 this(errorRate, null);
53 }
54
55 public LossyCounting(double errorRate, LossyCountingListener listener) {
56 if (errorRate < 0.0 || errorRate > 1.0) {
57 throw new IllegalArgumentException(" Lossy Counting error rate should be within range [0,1]");
58 }
59 this.bucketSize = (long) Math.ceil(1 / errorRate);
60 this.currentTerm = 1;
61 this.totalDataCount = 0;
62 this.data = new ConcurrentHashMap<>();
63 this.listener = listener;
64 calculateCurrentTerm();
65 }
66
67 LossyCounting(Configuration conf) {
68 this(conf, null);
69 }
70
71 public LossyCounting(Configuration conf, LossyCountingListener listener) {
72 this(conf.getDouble(HConstants.DEFAULT_LOSSY_COUNTING_ERROR_RATE, 0.02), listener);
73 }
74
75 private void addByOne(String key) {
76
77
78 Integer i = data.get(key);
79 if (i == null) {
80 i = currentTerm != 0 ? currentTerm - 1 : 0;
81 }
82 data.put(key, i + 1);
83
84 totalDataCount++;
85 calculateCurrentTerm();
86 }
87
88 public void add(String key) {
89 addByOne(key);
90 if (totalDataCount % bucketSize == 0) {
91
92 sweep();
93 }
94 }
95
96
97
98
99
100 private void sweep() {
101 for(Map.Entry<String, Integer> entry : data.entrySet()) {
102 if(entry.getValue() < currentTerm) {
103 String metric = entry.getKey();
104 data.remove(metric);
105 if (listener != null) {
106 listener.sweep(metric);
107 }
108 }
109 }
110 }
111
112
113
114
115 private void calculateCurrentTerm() {
116 this.currentTerm = (int) Math.ceil(1.0 * totalDataCount / (double) bucketSize);
117 }
118
119 public long getBucketSize(){
120 return bucketSize;
121 }
122
123 public long getDataSize() {
124 return data.size();
125 }
126
127 public boolean contains(String key) {
128 return data.containsKey(key);
129 }
130
131 public Set<String> getElements(){
132 return data.keySet();
133 }
134
135 public long getCurrentTerm() {
136 return currentTerm;
137 }
138 }
139