Atomic Values
Atomic values use CAS-like (Compare-and-Swap) techniques to ensure that operations on variables are atomic. Which means that when an operation is performed, the operation either fully succeeds or fully fails.
Atomic values are high-performance, thread-safe alternatives to other synchronization mechanisms like locks.
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
final AtomicInteger counter = new AtomicInteger(0);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
counter.set(counter.get() + 1);
}).start();
}
System.out.println(counter.get());
}
}