-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path37.DesignADistributedCounter.java
More file actions
75 lines (61 loc) · 1.65 KB
/
37.DesignADistributedCounter.java
File metadata and controls
75 lines (61 loc) · 1.65 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
68
69
70
71
72
73
74
75
import java.util.*;
class Node {
private int id;
private int[] counter;
private Network network;
public Node(int id, int totalNodes, Network network) {
this.id = id;
this.counter = new int[totalNodes];
this.network = network;
this.network.register(this);
}
public void increment() {
counter[id]++;
network.broadcast(this, counter);
}
public void decrement() {
counter[id]--;
network.broadcast(this, counter);
}
public void merge(int[] incoming) {
for (int i = 0; i < counter.length; i++) {
counter[i] = Math.max(counter[i], incoming[i]);
}
}
public int getValue() {
int sum = 0;
for (int x : counter) sum += x;
return sum;
}
public int[] getState() {
return counter.clone();
}
}
class Network {
private List<Node> nodes = new ArrayList<>();
public void register(Node node) {
nodes.add(node);
}
public void broadcast(Node sender, int[] state) {
for (Node n : nodes) {
if (n != sender) {
n.merge(state);
}
}
}
}
public class DistributedCounterDemo {
public static void main(String[] args) {
Network net = new Network();
Node A = new Node(0, 3, net);
Node B = new Node(1, 3, net);
Node C = new Node(2, 3, net);
A.increment();
A.increment();
B.increment();
C.decrement();
System.out.println("A value: " + A.getValue());
System.out.println("B value: " + B.getValue());
System.out.println("C value: " + C.getValue());
}
}