-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMppRunnerCode.java
More file actions
83 lines (69 loc) · 2.07 KB
/
Copy pathMppRunnerCode.java
File metadata and controls
83 lines (69 loc) · 2.07 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
76
77
78
79
80
81
82
83
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.*;
class MppRunnerCode {
private final int numShards;
private final Lock[] localLocks;
private final Map<String, Integer>[] localData;
private final Lock globalLock;
private final AtomicInteger globalCounter;
private int localReads = 0;
private int localWrites = 0;
public MppRunnerCode(int numShards) {
this.numShards = numShards;
this.localLocks = new ReentrantLock[numShards];
this.localData = new ConcurrentHashMap[numShards];
for (int i = 0; i < numShards; i++) {
this.localLocks[i] = new ReentrantLock();
this.localData[i] = new ConcurrentHashMap<>();
}
this.globalLock = new ReentrantLock();
this.globalCounter = new AtomicInteger(0);
}
private int getShardIndex(String key) {
return Math.abs(key.hashCode()) % numShards;
}
public void localWrite(String key, int value) {
int shardIndex = getShardIndex(key);
localLocks[shardIndex].lock();
try {
localData[shardIndex].merge(key, value, Integer::sum);
localWrites++;
} finally {
localLocks[shardIndex].unlock();
}
}
public Integer localRead(String key) {
int shardIndex = getShardIndex(key);
localLocks[shardIndex].lock();
try {
localReads++;
return localData[shardIndex].getOrDefault(key, null);
} finally {
localLocks[shardIndex].unlock();
}
}
public void criticalUpdate(int increment) {
globalLock.lock();
try {
globalCounter.addAndGet(increment);
} finally {
globalLock.unlock();
}
}
public void hybridOperation(String key, int value) {
localWrite(key, value);
criticalUpdate(value);
}
public void printStats() {
System.out.println("Total Reads: " + localReads + ", Total Writes: " + localWrites);
}
public int getGlobalCounter() {
return globalCounter.get();
}
public int getTotalLocalSum() {
return Arrays.stream(localData).mapToInt(shard -> shard.values().stream().mapToInt(Integer::intValue).sum())
.sum();
}
}