Junior — Middle
What methods and tools would you use to create a thread-safe counter?
sobes.tech AI
Answer from AI
To create a thread-safe counter in Java, you can use several approaches:
- AtomicInteger class from the
java.util.concurrent.atomicpackage. It provides atomic operations such asincrementAndGet(), which guarantee correct counter updates in a multithreaded environment without explicit synchronization.
import java.util.concurrent.atomic.AtomicInteger;
public class SafeCounter {
private AtomicInteger counter = new AtomicInteger(0);
public int increment() {
return counter.incrementAndGet();
}
public int get() {
return counter.get();
}
}
- Synchronization using the
synchronizedkeyword. You can make the increment and get methods synchronized to ensure exclusive access:
public class SafeCounter {
private int counter = 0;
public synchronized int increment() {
return ++counter;
}
public synchronized int get() {
return counter;
}
}
- Using
LongAdder— more efficient under high contention, as it reduces locking.
The choice depends on specific requirements: for simplicity and good performance, AtomicInteger is usually sufficient.