Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Member-only story

Atomic Classes in Java: A Paradigm of Lock-Free Utility Classes

ByteCook
Dev Genius
Published in
10 min readJun 30, 2024

--

Earlier, we frequently mentioned an example of an accumulator. The sample code is as follows. In this example, the add10K() method is not thread-safe. The problem lies in the visibility of the variable count and the atomicity of the count += 1 operation. The visibility issue can be solved using the volatile keyword, while the atomicity issue has traditionally been addressed using mutual exclusion locks.

public class Test {
long count = 0;
void add10K() {
int idx = 0;
while(idx++ < 10000) {
count += 1;
}
}
}

For simple atomicity issues, there is a lock-free solution. The Java SDK’s concurrency package encapsulates and refines this lock-free solution, resulting in a series of atomic classes. However, before delving into the implementation of atomic classes, let’s see how to use them to solve the accumulator problem. This will give you a preliminary understanding of atomic classes.

In the code below, we replace the original long variable count with the atomic class AtomicLong, and replace the original count += 1 with count.getAndIncrement(). With just these two simple changes, the add10K() method becomes thread-safe. Using atomic classes is quite straightforward.

public class Test {
AtomicLong count =
new AtomicLong(0);
void add10K() {
int idx = 0;
while(idx++ < 10000) {
count.getAndIncrement();
}
}
}

The biggest advantage of a lock-free solution over a mutual exclusion (mutex) solution is performance. The mutex solution ensures mutual exclusion by executing lock and unlock operations, which themselves consume performance. Additionally, threads that fail to acquire the lock enter a blocked state, triggering thread context switches, which also significantly impact performance. In contrast, the lock-free solution avoids the performance overhead of lock and unlock operations entirely, while still ensuring mutual exclusion. It solves the problem without introducing new issues, making it an excellent solution. But how does it achieve this?

The implementation principle of lock-free solutions

Actually, the secret behind the high performance of atomic classes is simple: hardware support. To…

--

--

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by ByteCook

My interests are wide-ranging, covering topics such as frontend and backend development, DevOps, software architecture, a bit of economics and finance

No responses yet

Write a response