-
Notifications
You must be signed in to change notification settings - Fork 2
/
G-Counter.java
69 lines (54 loc) · 1.42 KB
/
G-Counter.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
CRDT Datatype: G-Counter
*/
package crdt.counters;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static java.lang.Math.max;
import crdt.CRDT;
/**
* Grow only counter. Can only be incremented
*/
public class GCounter<T> implements CRDT<GCounter<T>> {
private static final long serialVersionUID = 1L;
private Map<T, Integer> counts = new HashMap<T, Integer>();
/**
* Increment a given key
*/
public void increment(T key) {
Integer count = counts.get(key);
if( count == null )
count = 0;
counts.put(key, count + 1);
}
/**
* Get the counter value
*/
public int get() {
int sum = 0;
for(int count: counts.values())
sum += count;
return sum;
}
/**
* Merge another counter into this one
*/
public void merge(GCounter<T> other) {
for(Entry<T, Integer> e: other.counts.entrySet()) {
T key = e.getKey();
if( counts.containsKey(key) )
counts.put(key, max(e.getValue(), counts.get(key)) );
else
counts.put(key, e.getValue());
}
}
public String toString() {
return "GCounter{" + counts + "}";
}
public GCounter<T> copy() {
GCounter<T> copy = new GCounter<T>();
copy.counts = new HashMap<T, Integer>(counts);
return copy;
}
}