20 lines
799 B
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();
|
|
}
|
|
} |