-
Notifications
You must be signed in to change notification settings - Fork 7
/
LocalNamedCounters.java
54 lines (45 loc) · 1.37 KB
/
LocalNamedCounters.java
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
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.biz.cluster.work;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Provides local (single machine) implementation for a set of counters.
*/
class LocalNamedCounters implements NamedCounters {
private final Map<String, AtomicInteger> counters = new HashMap<>();
@Override
public long incrementAndGet(String counter) {
synchronized (counters) {
return counters.computeIfAbsent(counter, ignored -> new AtomicInteger(0)).incrementAndGet();
}
}
@Override
public long get(String counter) {
synchronized (counters) {
AtomicInteger value = counters.get(counter);
return value == null ? 0 : value.get();
}
}
@Override
public long decrementAndGet(String counter) {
synchronized (counters) {
AtomicInteger value = counters.get(counter);
if (value == null) {
return 0;
}
int decrementedValue = value.decrementAndGet();
if (decrementedValue <= 0) {
counters.remove(counter);
return 0;
}
return decrementedValue;
}
}
}