Senior
Task on multithreading: thread-safe metric collector with efficient increment, key — string, value — counter.
sobes.tech AI
Answer from AI
For a thread-safe metric collector with a string key and counter value in Java, you can use ConcurrentHashMap<String, AtomicLong>.
ConcurrentHashMapprovides concurrent access without locks at the entire map level.AtomicLongallows efficient and atomic incrementing of the counter.
Example implementation:
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
public class MetricsCollector {
private final ConcurrentHashMap<String, AtomicLong> counters = new ConcurrentHashMap<>();
public void increment(String key) {
counters.computeIfAbsent(key, k -> new AtomicLong()).incrementAndGet();
}
public long getCount(String key) {
AtomicLong count = counters.get(key);
return count != null ? count.get() : 0L;
}
}
This approach minimizes locking and ensures high performance under multithreaded access.