JAVA: atomic vs synchronized

JAVA: atomic vs synchronized

It's been always said to use atomic whenever possible instead of other synchronization mechanisms. It's claimed atomic outperforms the other ones. But is that really true?

Let's take as an example two possible implementations of Counter that can be found in my previous posts.

JAVA: synchronized
Let’s imagine, we are writing a program that reads events from the network. Then performs computations based on what’s been received. Possibly, a simplified Event could look like that. public class Event { private final String name; private final String content; Event(String name, Str…
JAVA: atomic
When solving software engineering challenges, in most cases there is no single solution. Rather than, there are always a bunch of them. Each approach is unique and has some limitations. Last time I wrote about synchronized keyword as a way to avoid race conditions. You can find the article below.

We have two slightly different implementations. The first one uses synchronized.

public class Counter {
    private int cnt = 0;

    public synchronized int getCnt() {
        return cnt;
    }

    public synchronized void inc() {
        ++cnt;
    }
}

And the other one using AtomicInteger.

public class Counter {
    private final AtomicInteger cnt = new AtomicInteger();

    public int getCnt() {
        return cnt.get();
    }

    public void inc() {
        cnt.incrementAndGet();
    }
}

That's a really good starting point. Now, we need to have measures to compare them. For that purpose, we will use Java Microbenchmark Harness (JMH). JMH will allow us to write benchmarks to compare the average execution time of methods.