refactor AcceptanceRateTracker to use a custom Counter class
Then means we do far fewer puts to the Map, which is more performant
@@ -8,14 +8,13 @@ import java.util.Map;
public class AcceptanceRateTracker implements ProposalListener {
- private Map<VertexId, Integer> numApplied = Maps.newHashMap();
- private Map<VertexId, Integer> numRejected = Maps.newHashMap();
+ private Map<VertexId, Counter> numApplied = Maps.newHashMap();
+ private Map<VertexId, Counter> numRejected = Maps.newHashMap();
@Override
public void onProposalApplied(Proposal proposal) {
for (Vertex vertex : proposal.getVerticesWithProposal()) {
- Integer previousValue = numApplied.getOrDefault(vertex.getId(), 0);
- numApplied.put(vertex.getId(), previousValue + 1);
+ numApplied.computeIfAbsent(vertex.getId(), i -> new Counter()).increment();
}
}
@@ -23,14 +22,25 @@ public class AcceptanceRateTracker implements ProposalListener {
if (!numApplied.keySet().contains(vertexId)) {
throw new IllegalStateException("No proposals have been registered for " + vertexId);
}
- return 1. - (double) numRejected.getOrDefault(vertexId, 0) / numApplied.get(vertexId);
+ return 1. - (double) numRejected.getOrDefault(vertexId, new Counter()).getValue() / numApplied.get(vertexId).getValue();
}
@Override
public void onProposalRejected(Proposal proposal) {
for (Vertex vertex : proposal.getVerticesWithProposal()) {
- Integer previousValue = numRejected.getOrDefault(vertex.getId(), 0);
- numRejected.put(vertex.getId(), previousValue + 1);
+ numRejected.computeIfAbsent(vertex.getId(), i -> new Counter()).increment();
+ }
+ }
+
+ private class Counter {
+ private int count;
+
+ int getValue() {
+ return count;
+ }
+
+ int increment() {
+ return count++;
}
}
}
