Sobes.tech
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:

  1. AtomicInteger class from the java.util.concurrent.atomic package. It provides atomic operations such as incrementAndGet(), 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();
    }
}
  1. Synchronization using the synchronized keyword. 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;
    }
}
  1. 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.

What methods and tools would you use to create a… - sobes.tech