This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
PF3/hw2/Ex2/src/ConcurrentVoteCounter.java

20 lines
799 B
Java

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
public class ConcurrentVoteCounter implements VoteCounter {
private final ConcurrentMap<Integer, AtomicInteger> electionResults = new ConcurrentHashMap<>();
public void addVote(Integer id) {
// Alternative implementation (using plain Integers, slower due to synchronization costs):
// electionResults.compute(id, (k, v) -> v != null ? v + 1 : 1);
// Faster version due to architecture-level optimization
electionResults.putIfAbsent(id, new AtomicInteger(0));
electionResults.get(id).addAndGet(1);
}
public Integer getVoteCount(Integer id) {
return electionResults.get(id).intValue();
}
}