Unlock High-Performance Java with Lock-Free Concurrency and Atomic Classes
This article explains how lock-free techniques such as Compare-And-Swap (CAS) and Java's atomic classes—including AtomicBoolean, AtomicInteger, AtomicReference, and their array and field updaters—provide optimistic concurrency control, reduce context switches, and improve performance compared to traditional locking mechanisms.
1. Background
Through previous learning we know two main ways to ensure data safety and consistency in multithreaded concurrency: locking and ThreadLocal. Locking trades time for space, while ThreadLocal trades space for time.
Is there a way to achieve concurrency without using locks? Yes. The following introduces lock-free concepts and common classes.
2. Lock-Free
Thread switching requires context switching, which saves the state of the previous task and restores it later. Context switches consume time and resources, so reducing them improves multithreaded efficiency. Lock-free techniques aim to reduce context switches.
Locks are a pessimistic strategy that assumes conflicts and blocks threads, whereas lock-free is optimistic, assuming no conflicts and allowing threads to proceed without waiting.
When conflicts occur, lock-free uses Compare-And-Swap (CAS) to detect and retry the operation until it succeeds.
3. What is Compare-And-Swap (CAS)
Compared with locks, CAS makes programs more complex but provides non-blocking behavior, immunity to deadlocks, and lower inter-thread interference. It eliminates lock competition overhead and scheduling costs, offering superior performance.
Advantages of lock-free:
1. Better performance under high concurrency;
2. Naturally immune to deadlocks.CAS operates with three parameters CAS(V, E, N): V is the variable to update, E is the expected value, and N is the new value. The update succeeds only if V equals E; otherwise, V remains unchanged and CAS returns the current value of V.
CAS works optimistically: only one thread succeeds while others fail and may retry. It requires providing an expected value; if the variable has changed, the operation is retried.
Modern processors support atomic CAS instructions, and since JDK 5.0 the JVM can use them for concurrent data structures.
4. Java Atomic Classes
Java provides atomic classes in the java.util.concurrent.atomic package, divided into four categories: atomic primitive types, atomic array types, atomic reference types, and atomic field updaters. These classes implement lock-free operations using CAS.
Images illustrating the package structure:
5. Atomic Primitive Types
AtomicBoolean – atomic boolean updates
AtomicInteger – atomic integer updates
AtomicLong – atomic long updates
All follow similar principles; the following focuses on AtomicInteger.
Example generating 10,000 integers and printing them.
The method incrementAndGet() works as follows:
It reads the current volatile value, computes int next = current + 1;, and attempts compareAndSet(current, next) inside a loop until successful.
int next = current + 1;
if (compareAndSet(current, next)) {
return next;
}The underlying CAS call maps to Unsafe.compareAndSwapInt(), which is the core of Java's atomic operations.
6. Atomic Reference Types
AtomicReference – atomic reference updates
AtomicStampedReference – atomic reference with version stamp
AtomicMarkableReference – atomic reference with boolean mark
AtomicReference ensures thread-safe updates of object references. However, without a version stamp, it cannot detect state migrations, leading to potential inconsistencies.
AtomicStampedReference adds a timestamp to the reference, allowing updates only when both the expected value and stamp match, thus preventing lost updates.
Result shows that each account is recharged only once.
7. Atomic Array Types
AtomicIntegerArray – atomic updates of integer array elements
AtomicLongArray – atomic updates of long array elements
AtomicReferenceArray – atomic updates of reference array elements
Simple example:
8. Atomic Field Updaters
AtomicIntegerFieldUpdater – atomic updates of integer fields
AtomicLongFieldUpdater – atomic updates of long fields
AtomicReferenceFieldUpdater – atomic updates of reference fields
Example usage:
Reference: http://www.cnblogs.com/756623607-zhang/p/6876060.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
