-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathImpressionCounter.java
More file actions
67 lines (53 loc) · 2.08 KB
/
Copy pathImpressionCounter.java
File metadata and controls
67 lines (53 loc) · 2.08 KB
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
package io.split.client.impressions;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class ImpressionCounter {
public static class Key {
private final String _featureName;
private final long _timeFrame;
public Key(String featureFlagName, long timeframe) {
_featureName = Objects.requireNonNull(featureFlagName);
_timeFrame = timeframe;
}
public String featureName() { return _featureName; }
public long timeFrame() { return _timeFrame; }
@Override
public int hashCode() {
return Objects.hash(_featureName, _timeFrame);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return Objects.equals(_featureName, key._featureName) && Objects.equals(_timeFrame, key._timeFrame);
}
}
private final ConcurrentHashMap<Key, AtomicInteger> _counts;
public ImpressionCounter() {
_counts = new ConcurrentHashMap<>();
}
public void inc(String featureFlagName, long timeFrame, int amount) {
Key key = new Key(featureFlagName, ImpressionUtils.truncateTimeframe(timeFrame));
AtomicInteger count = _counts.get(key);
if (Objects.isNull(count)) {
count = new AtomicInteger();
AtomicInteger old = _counts.putIfAbsent(key, count);
if (!Objects.isNull(old)) { // Some other thread won the race, use that AtomicInteger instead
count = old;
}
}
count.addAndGet(amount);
}
public HashMap<Key, Integer> popAll() {
HashMap<Key, Integer> toReturn = new HashMap<>();
for (Key key : _counts.keySet()) {
AtomicInteger curr = _counts.remove(key);
toReturn.put(key, curr.get());
}
return toReturn;
}
public boolean isEmpty() { return _counts.isEmpty(); }
}