JUC Concurrent Programming
This article introduces the core concepts of Java multithreading and concurrent programming. It first explains the basic concepts of processes as units of resource allocation and threads as units of execution, as well as the difference between concurrency and parallelism. It then details three ways to create threads in Java (Thread, Runnable, and FutureTask) and thread state management. It focuses on how the synchronized keyword works, including the Monitor mechanism, lock escalation (unlocked → biased → lightweight → heavyweight), and optimization strategies such as lock spinning and lock elimination. It explains how the volatile keyword uses memory barriers to ensure visibility and ordering, and covers the wait-notify mechanism. It also describes the CAS approach to lock-free programming and compares optimistic and pessimistic locks. Finally, it introduces the atomic classes in the Java.util.concurrent.atomic package, including basic atomic classes, atomic references, atomic arrays, atomic field updaters, and atomic accumulators, showing how CAS enables efficient thread-safe operations.
1. Concepts:
1.1 Processes and Threads
Process:
For a program (a static file on disk) to run, its resources must be loaded into memory, after which its instructions can be executed. At this point, a process is started.
A process can be considered an instance of a program (a program can have multiple process instances).
In Windows, a process is inactive and serves only as a container for threads.
Thread:
A thread is a stream of instructions, or a path of execution. (A process can have one or more threads.)
In Java, a thread is the smallest unit of scheduling, while a process is the smallest unit of resource allocation.
Memory and I/O resources are managed at the process level; instructions are executed at the thread level.
The cost of switching process context is higher than that of switching thread context.
Communication methods
Processes on the same computer can communicate using IPC (inter-process communication). Different computers need to communicate over a network and through higher-level protocols. Compared with processes, threads share resources such as memory, making communication more convenient.
1.2 Concurrency and Parallelism
Time-sharing:
The operating system's time scheduler allocates CPU time slices (with a minimum of 15 ms in Windows) to different threads.
When a single CPU core takes turns processing tasks from multiple threads, this is called concurrent execution.
When multiple CPU cores process tasks from multiple threads at the same time, this is called concurrent parallel execution.
Multicore CPUs typically support both concurrency and parallelism.
Concurrency:
<img src="/api/file/69cf17debf8448c3b3324b912aae3875_0.7.jpg" alt="image-20240806221021880" style="height:300px" />
Parallelism:
<img src="/api/file/69d53409cd264c17988166a329debe0c_0.7.jpg" alt="image-20240806220937567" style="height:300px" />
1.3 Synchronous and Asynchronous
In terms of method calls:
Synchronous async: You must wait for the method to return a result before continuing.
Asynchronous sync: You can continue without waiting for the method to return a result.
On a single-core CPU, multithreading can actually be slower than single-threading due to the overhead of context switching. However, this does not mean multithreading is pointless on a single-core CPU. In some cases, blocking must be avoided, making multithreading essential.
I/O operations do not occupy the CPU, but copying files (blocking I/O) requires the CPU to wait, preventing it from being fully utilized. (This can be optimized using non-blocking I/O and asynchronous I/O.)
Ways to implement multithreading in Java
Thread
Thread thread = new Thread() { @Override public void run() { log.info("running"); } }; thread.start(); log.info("running");Runnable (more flexible and easier to use with thread pools)
Runnable runnable = new Runnable() { public void run() { log.info("Hello World"); } }; Thread thread = new Thread(runnable) ; thread.start(); log.info("running");FutureTask + Callable (can return a result)
FutureTask<Integer> futureTask = new FutureTask<>(() -> { log.info("running"); Thread.sleep(1000); return 100; }); new Thread(futureTask).start(); log.info("finished"); Integer i = futureTask.get(); System.out.println(i); log.info("done");
2. Process Management
Windows:
- Use Task Manager;
- Use
tasklistto view all processes taskkillcommand:taskkill /F /PID \<pid>
Linux:
ps -feto view all processes;ps -fT -p \<pid>to view information about the process corresponding to the PID;killto terminate a process;- Use
topand press uppercase H to display threads.
Java
jpsto view all Java processesjconsolefor graphical monitoringjstack \<pid>to view the states of all threads in a Java process
Allow remote connections to a Java program using JConsole. Startup parameters:
-Djava.rmi.server.hostname=192.168.1.1
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=20001
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
3. Stacks and Stack Frames
Java Virtual Machine Stacks (Java Virtual Machine Stacks)
The JVM consists of the heap, stack, and method area. The stack memory is allocated for use by threads. A stack is made up of multiple stack frames, but only one stack frame is active at a time, corresponding to the active method.
<img src="/api/file/b0514d1d49d74d3d877db77db1384cdc_0.7.jpg" alt="image-20250809140240371" style="zoom:50%;" />4. Threads
4.1 Context Switching
The following situations cause the CPU to stop executing the current thread (a context switch) and switch to executing code from another thread:
- The thread's time slice expires
- Garbage collection
- A higher-priority thread needs to run
- The thread itself calls methods such as
sleep,yield,wait,join,park,synchronized, orlock
When a context switch occurs, the current thread's state must be saved (the program counter and information for each stack frame, such as local variables, the operand stack, and the return address).
Frequent context switches affect performance. (More threads are not always better.)
4.2 Thread Class API
| Method | Description |
|---|---|
| public void start() | Starts a new thread. The Java Virtual Machine calls this thread's run method. |
| public void run() | Called after the thread starts. |
| public void setName(String name) | Sets the name of the current thread. |
| public void getName() | Gets the name of the current thread. Threads have default names: child threads are named Thread-index, and the main thread is named main. |
| public static Thread currentThread() | Gets the current thread object; indicates which thread the code is executing in. |
| public static void sleep(long time) | Puts the current thread to sleep for a specified number of milliseconds before continuing. Thread.sleep(0): prompts the operating system to immediately perform another CPU scheduling competition. |
| public static native void yield() | Hints to the thread scheduler to yield the current thread's use of the CPU. |
| public final int getPriority() | Returns this thread's priority. |
| public final void setPriority(int priority) | Changes this thread's priority; commonly used values are 1, 5, and 10. |
| public void interrupt() | Interrupts this thread; uses the exception-handling mechanism. |
| public static boolean interrupted() | Checks whether the current thread has been interrupted and clears the interrupt flag. |
| public boolean isInterrupted() | Checks whether the current thread has been interrupted without clearing the interrupt flag. |
| public final void join() | Waits for this thread to finish. |
| public final void join(long millis) | Waits for this thread to terminate for millis milliseconds; 0 means wait forever. |
| public final native boolean isAlive() | Indicates whether the thread is alive (has not finished running). |
| public final void setDaemon(boolean on) | Marks this thread as a daemon thread or a user thread. |
4.3 Thread States
At the operating system level, there are five states:
<img src="/api/file/ebf446cb1cdc4c36834a6c836f19c712_0.7.jpg" alt="image-20250809142600760" style="zoom:50%;" />
At the Java level, Thread.state defines six states:
5. Synchonized
Synchonized uses an object lock to guarantee the atomicity of code in a critical section.
Critical Sections
Critical resource: A resource that can be used by only one process at a time is called a critical resource.
Critical section: A block of code that accesses a critical resource.
Race condition: When multiple threads execute within a critical section, and differences in the order of code execution make the result unpredictable, a race condition is said to have occurred.
Running multiple threads in a program is not a problem, and neither is having multiple threads read a shared resource. Problems arise when instructions become interleaved as multiple threads read from and write to a shared resource.
To prevent race conditions in critical sections (and solve thread-safety issues):
- Blocking solutions:
synchronized,lock - Non-blocking solutions: atomic variables
Monitor
A software module consisting of a number of local shared variables and all the procedures that access those variables. It ensures that only one process at a time is active within the monitor; in other words, an operation defined in the monitor can be called by only one process at a time (implemented by the compiler).
synchronized: an object lock that guarantees the atomicity of code within a critical section. It uses mutual exclusion so that at most one thread can hold the object lock at any given time. Other threads that try to acquire the lock are blocked, ensuring that the thread holding the lock can safely execute the code in the critical section without worrying about thread context switches.
Both mutual exclusion and synchronization can be implemented using the synchronized keyword. The difference is:
- Mutual exclusion ensures that race conditions in critical sections do not occur: only one thread can execute the critical-section code at a time.
- Synchronization is needed when differences in the order or sequence of thread execution mean that one thread must wait for another thread to reach a certain point.
Performance:
- Thread-safe, but poor performance
- Not thread-safe, but good performance. If there are no thread-safety issues involving multiple threads in your development context, it is recommended to use a non-thread-safe design class.
Lock Upgrades

Unlocked -> Biased Lock -> Lightweight Lock -> Heavyweight Lock // As contention increases, locks can only be upgraded, not downgraded.
Lightweight Locks
When multiple threads need to lock an object, but their locking times are staggered (there is no contention), a lightweight lock can be used as an optimization. Lightweight locks are transparent to users (invisible).
Reentrant lock: A thread can enter any code block synchronized on a lock it already owns. The greatest benefit of a reentrant lock is that it avoids deadlocks.
When there is no contention, even when a lock is reentered, a lightweight lock still requires a CAS operation for each reentry. Biased locks, introduced in Java 6, optimize this.
Example of lock reentry:
static final Object obj = new Object();
public static void method1() {
synchronized( obj ) {
// 同步块 A
method2();
}
}
public static void method2() {
synchronized( obj ) {
// 同步块 B
}
}
Create a Lock Record object. Each thread’s stack frame contains a Lock Record structure that stores the locked object’s Mark Word. Set the Lock Record’s Object reference to point to the locked object, then attempt to use CAS to replace the Object’s Mark Word and store the Mark Word value in the Lock Record.
<img src="/api/file/c3358eab80334cd2b8abc89af33671de_0.7.jpg" alt="image-20250809203351535" style="zoom:50%;" />If the CAS replacement succeeds, the object header stores the Lock Record address and state
<img src="/api/file/321d06a7448a4d55922b3d1ab242e083_0.7.jpg" alt="image-20250809203426374" style="zoom:50%;" />00(lightweight lock), indicating that the thread has locked the object.If the CAS fails, there are two possibilities:
- If another thread already holds a lightweight lock on the Object, this indicates contention, and the lock inflation process begins.
- If the thread itself is reentering a
synchronizedlock, add a Lock Record to track the reentrant lock count. <img src="/api/file/a17729c825c04b6db7042cb992a88057_0.7.jpg" alt="image-20250809203439223" style="zoom:50%;" />
When exiting the
synchronizedblock (unlocking):If there is a Lock Record whose value is
null, this indicates reentrancy. Reset the Lock Record to decrement the reentrancy count by 1.If the Lock Record’s value is not
null, use CAS torestore the Mark Word value to the object header.
- If successful, unlocking succeeds.
- If it fails, the lightweight lock has inflated or has already been upgraded to a heavyweight lock. Proceed with the heavyweight lock unlocking process.
Lock Inflation
During an attempt to acquire a lightweight lock, the CAS operation may fail because another thread has acquired a lightweight lock on the object (contention). In this case, the lock must be inflated, converting the lightweight lock into a heavyweight lock.
When Thread-1 attempts to acquire a lightweight lock, Thread-0 has already acquired a lightweight lock on the object.
<img src="/api/file/ef2dc1a504334d3296d86f192d8ae82a_0.7.jpg" alt="image-20250809203512052" style="zoom:50%;" />Thread-1 fails to acquire the lightweight lock and enters the lock inflation process: it requests a Monitor lock for the Object, obtains the lock-holding thread from the Object’s object header, sets the Monitor’s Owner to Thread-0, points the Object’s object header to the heavyweight lock address, and then enters the Monitor’s EntryList in the BLOCKED state.

When Thread-0 exits the synchronized block and unlocks, its attempt to use CAS to restore the Mark Word value to the object header fails. It then enters the heavyweight lock unlocking process: it finds the Monitor object using the Monitor address, sets Owner to null, and wakes the BLOCKED threads in the EntryList.
Lock Spinning
During heavyweight lock contention, a thread attempting to acquire the lock does not block immediately. It can use spinning (10 attempts by default) as an optimization, repeatedly trying to acquire the lock in a loop.
Note:
- Spinning uses CPU time. On a single-core CPU, spinning wastes time because only one thread can run at a time; spinning is beneficial only on a multicore CPU.
- Threads that fail to acquire the lock through spinning enter the blocked state.
Advantage: Threads do not enter the blocked state, reducing the overhead of thread context switching.
Disadvantage: As the number of spinning threads increases, they consume more and more CPU resources.
Lock Elimination
The JIT (Just-In-Time compiler) optimizes hot code by directly removing meaningless locking operations. This is called lock elimination.
Lock coarsening: Multiple lock/unlock code blocks for the same lock object are optimized into one larger code block, with locking and unlocking performed just once.
wait-notify
You must acquire the object lock before calling 锁对象.wait(). notify wakes up one thread at random, while notifyAll wakes up all threads to compete for CPU time.
Object class API:
public final void notify():唤醒正在等待对象监视器的单个线程。
public final void notifyAll():唤醒正在等待对象监视器的所有线程。
public final void wait():导致当前线程等待,直到另一个线程调用该对象的 notify() 方法或 notifyAll()方法。
public final native void wait(long timeout):有时限的等待, 到n毫秒后结束等待,或是被唤醒
说明:wait suspends a thread, so any operation that needs to wake it is a suspension operation. A blocked thread can try to acquire the lock on its own; a suspended thread must be woken before it can try to acquire the lock.
Compared with sleep():
- Different principles: The sleep() method belongs to the Thread class. A thread uses it to control its own execution flow, pausing execution for a period of time and yielding the opportunity to run to other threads. The wait() method belongs to the Object class and is used for communication between threads.
- Different lock-handling mechanisms: While a thread is calling sleep(), it does not release the object lock. When it calls wait(), it releases the object lock and enters that object's wait set to wait (if the lock were not released, how could another thread acquire it and perform the wake-up operation?). Both methods release the CPU, however.
- Different usage contexts: wait() must be used inside a synchronized method or synchronized block (after acquiring the lock), whereas sleep() can be used anywhere.
Underlying principles:
- When the Owner thread finds that a condition is not met, it can call wait() to enter the WaitSet and transition to the WAITING state.
- BLOCKED and WAITING threads are both in a blocked state and do not consume CPU time slices.
- A BLOCKED thread is woken when the Owner thread releases the lock.
- A WAITING thread is woken when the Owner thread calls notify or notifyAll. Waking up does not mean it immediately acquires the lock; it must enter the EntryList and compete for the lock again.
6.volatile
volatile is a lightweight synchronization mechanism provided by the Java Virtual Machine (one of the three key properties):
- Guarantees visibility
- Does not guarantee atomicity
- Guarantees ordering (prevents instruction reordering)
Performance: Read operations on variables declared volatile are almost no different from those on ordinary variables, but write operations are relatively slower because many memory barriers must be inserted into the native code to prevent out-of-order execution. However, the overhead is lower than that of locks.
synchronized cannot prevent instruction reordering or processor optimizations. Why, then, can it guarantee ordering and visibility?
- After a lock is acquired, only one thread can hold it. Threads that fail to acquire it are blocked, so only one thread runs at a time, which is equivalent to single-threaded execution. Due to data dependencies, instruction reordering in single-threaded execution is not a problem.
- Before a thread acquires a lock, the values of shared variables in its working memory are cleared; when it uses a shared variable, it must reread the latest value from main memory. Before a thread releases a lock, it must flush the latest values of shared variables to main memory (as described in the JMM memory interaction section).
Cache Coherence
For shared variables declared volatile, the underlying mechanism uses the lock prefix instruction in assembly to lock the cache. After a thread modifies a shared variable, it writes the change back to main memory. Threads running on other CPU cores use the CPU bus snooping mechanism to mark their copies of the shared variable as invalid. When they next read the variable, they retrieve the latest data from main memory.
The lock prefix instruction is equivalent to a memory barrier (Memory Barrier / Memory Fence).
- A write barrier is added after a write instruction to a volatile variable.
- A read barrier is added before a read instruction of a volatile variable.
Memory barriers have three functions:
- Ensure that read-modify-write operations on memory execute atomically.
- Prevent instruction reordering across the barrier.
- Force dirty data in the cache to be written back to main memory and invalidate the corresponding data in the cache line.
Memory Barriers
Guaranteeing visibility:
A write barrier (sfence, Store Barrier) ensures that all modifications to shared variables made before the barrier are synchronized to main memory.
public void actor2(I_Result r) { num = 2; ready = true; // ready 是 volatile 赋值带写屏障 // 写屏障 }A read barrier (
lfence, Load Barrier) ensures that reads of shared variables after the barrier refresh their values from main memory and load the latest data from main memory.public void actor1(I_Result r) { // 读屏障 // ready 是 volatile 读取值带读屏障 if(ready) { r.r1 = num + num; } else { r.r1 = 1; } }
Full barrier: mfence (modify/mix Barrier), which combines the functions of sfence and lfence
Guarantees ordering:
- A write barrier ensures that, during instruction reordering, code before the write barrier is not moved after it.
- A read barrier ensures that, during instruction reordering, code after the read barrier is not moved before it.
Does not prevent interleaving of instructions:
A write barrier only ensures that subsequent reads can see the latest result; it cannot prevent reads by other threads from occurring before the write barrier.
The ordering guarantee only ensures that related code within the current thread is not reordered.
volatile i = 0; new Thread(() -> {i++}); new Thread(() -> {i--});i++ instructions after decompilation:
0: iconst_1 // 当int取值 -1~5 时,JVM采用iconst指令将常量压入栈中 1: istore_1 // 将操作数栈顶数据弹出,存入局部变量表的 slot 1 2: iinc 1, 1
Interaction Rules
For variables modified with volatile:
- A thread’s use of a variable is associated with the load and read operations, so the variable must be loaded from main memory before it is used
- A thread’s assignment to a variable is associated with the store and write operations, so the variable must be synchronized to main memory after it is used
- Whichever of Thread 1 and Thread 2 performs the read operation on the variable first will perform the write operation first, preventing instruction reordering
Double-Checked Locking
The DCL (double-checked locking) mechanism is not necessarily thread-safe because instruction reordering can occur. Adding volatile can prevent instruction reordering.
public final class Singleton {
private Singleton() { }
private static Singleton INSTANCE = null;
public static Singleton getInstance() {
if(INSTANCE == null) { // t2,这里的判断不是线程安全的
// 首次访问会同步,而之后的使用没有 synchronized
synchronized(Singleton.class) {
// 这里是线程安全的判断,防止其他线程在当前线程等待锁的期间完成了初始化
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
Reasons for not locking INSTANCE:
INSTANCEneeds to be reassignedINSTANCEis null. Before a thread can acquire a lock, it needs to obtain a reference to the object and set the object header; null has no reference
Implementation characteristics:
- Lazy initialization
synchronizedis used only on the first call togetInstance(); subsequent calls do not need to acquire a lock- The first
ifuses theINSTANCEvariable outside the synchronized block, which can cause problems in a multithreaded environment
7. Lock-Free
CAS
Lock-free programming: Lock Free
CAS stands for Compare-And-Swap. It is a CPU concurrency primitive.
- In Java, CAS concurrency primitives are represented by the methods in the
sun.misc.Unsafeclass. When a CAS method in theUnsafeclass is called, the JVM generates a CAS assembly instruction. This functionality depends entirely on the hardware and implements atomic operations. - CAS is a system primitive. Primitives belong to the operating system domain and consist of several instructions that perform a specific function. A primitive must execute continuously and cannot be interrupted during execution. Therefore, CAS is an atomic CPU instruction that does not cause data inconsistency and is thread-safe.
Underlying principle: CAS is implemented using the lock cmpxchg instruction (x86 architecture), which guarantees the atomicity of compare-and-swap on both single-core and multicore CPUs.
- If the program runs on a single-core processor, the
lockprefix is omitted. A single processor maintains sequential consistency within the processor itself, so the memory-barrier effect of thelockprefix is unnecessary. - If the program runs on a multicore processor, the
lockprefix is added to thecmpxchginstruction. When a core executes an instruction with thelockprefix, the CPU performs a bus lock or cache lock, writing the modified variable to main memory. This process cannot be interrupted by the thread scheduler, ensuring the atomicity of memory operations across multiple threads.
Purpose: Compares the value in the current working memory with the value in main physical memory. If they are equal, it performs the specified operation; otherwise, it continues comparing until the values in main memory and working memory match.
CAS characteristics:
- CAS provides lock-free concurrency and non-blocking concurrency. Threads do not become blocked, and they do not need to switch states frequently (context switches or system calls).
- CAS is based on the optimistic locking approach.
CAS drawbacks:
- It performs a loop. If the comparison fails, it keeps looping. In the worst case, a thread may repeatedly obtain a value that differs from the expected value, resulting in an infinite loop and starvation. The number of threads using CAS should not exceed the number of CPU cores; segmented CAS and an automatic migration mechanism can be used.
- It can only guarantee atomic operations on a single shared variable.
- When operating on a single shared variable, atomicity can be ensured using a CAS loop.
- When operating on multiple shared variables, a CAS loop cannot guarantee atomicity; a lock must be used to ensure atomicity.
- It gives rise to the ABA problem.
Optimistic Locking
Summary of CAS and synchronized:
synchronizedtakes a pessimistic approach: it always assumes the worst and assumes that others will modify the data whenever it is accessed. Therefore, it locks every time the data is accessed. Other threads trying to access the data will be blocked (a shared resource is used by only one thread at a time; other threads are blocked, and the resource is transferred to another thread when it is no longer needed). Thus,synchronizedis also called a pessimistic lock.ReentrantLockis also a pessimistic lock, with relatively poor performance.- CAS takes an optimistic approach: it always assumes the best and assumes that others will not modify the data whenever it is accessed, so it does not lock. However, when updating, it checks whether another thread has updated the data in the meantime. If another thread has modified it, the latest value is retrieved; if not, the shared data is modified directly. This mechanism is also called optimistic locking and generally offers better performance.
8. Atomic
Common atomic classes: AtomicInteger, AtomicBoolean, AtomicLong
Constructors:
public AtomicInteger(): Initializes an atomic Integer with a default value of 0public AtomicInteger(int initialValue): Initializes an atomic Integer with a specified value
Common APIs:
| Method | Purpose |
|---|---|
| public final int get() | Gets the value of AtomicInteger |
| public final int getAndIncrement() | Atomically increments the current value by 1 and returns the value before incrementing |
| public final int incrementAndGet() | Atomically increments the current value by 1 and returns the value after incrementing |
| public final int getAndSet(int value) | Atomically sets the value to newValue and returns the old value |
| public final int addAndGet(int data) | Atomically adds the input value to the instance value and returns the result. Instance: the value in AtomicInteger |
Principle Analysis
AtomicInteger principle: spin lock + CAS algorithm
CAS algorithm: There are 3 operands (memory value V, old expected value A, value B to be written)
- If the old expected value A == memory value V, the value can be modified: V is changed to B.
- If the old expected value A != memory value V, the value cannot be modified. The latest value is fetched again; this repeated fetching is the spin.
Analysis of the getAndSet method:
AtomicInteger:
public final int getAndSet(int newValue) { /** * this: 当前对象 * valueOffset: 内存偏移量,内存地址 */ return unsafe.getAndSetInt(this, valueOffset, newValue); }valueOffset: The offset indicates the variable value’s position relative to the current object’s address. Unsafe uses this memory offset to retrieve the data.
valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); //调用本地方法 --> public native long objectFieldOffset(Field var1);unsafe class:
// val1: AtomicInteger对象本身,var2: 该对象值得引用地址,var4: 需要变动的数 public final int getAndSetInt(Object var1, long var2, int var4) { int var5; do { // var5: 用 var1 和 var2 找到的内存中的真实值 var5 = this.getIntVolatile(var1, var2); } while(!this.compareAndSwapInt(var1, var2, var5, var4)); return var5; }var5: Copy the value from main memory to working memory (fetch the latest value from main memory each time), then execute
compareAndSwapInt()and compare it with the value in main memory. If the method returns false, keep executing the while method until the expected value matches the actual value, then modify the data.The variable
valueis declaredvolatile, ensuring memory visibility across threads and preventing threads from retrieving stale variables from their working caches.private volatile int valueCAS must rely on volatile to read the latest value of a shared variable and perform a compare-and-swap operation
Analyze the getAndUpdate method:
getAndUpdate:
public final int getAndUpdate(IntUnaryOperator updateFunction) { int prev, next; do { prev = get(); //当前值,cas的期望值 next = updateFunction.applyAsInt(prev);//期望值更新到该值 } while (!compareAndSet(prev, next));//自旋 return prev; }Functional interface: Custom operation logic can be defined.
AtomicInteger a = new AtomicInteger(); a.getAndUpdate(i -> i + 10);compareAndSet:
public final boolean compareAndSet(int expect, int update) { /** * this: 当前对象 * valueOffset: 内存偏移量,内存地址 * expect: 期望的值 * update: 更新的值 */ return unsafe.compareAndSwapInt(this, valueOffset, expect, update); }
Atomic References
Atomic reference: Performs atomic operations on an Object, providing an object reference variable whose reads and writes are atomic.
Atomic reference classes: AtomicReference, AtomicStampedReference, AtomicMarkableReference
AtomicReference class:
- Constructor:
AtomicReference<T> atomicReference = new AtomicReference<T>() - Common APIs:
public final boolean compareAndSet(V expectedValue, V newValue): CAS operationpublic final void set(V newValue): Sets the value to newValuepublic final V get(): Returns the current value
public class AtomicReferenceDemo {
public static void main(String[] args) {
Student s1 = new Student(33, "z3");
// 创建原子引用包装类
AtomicReference<Student> atomicReference = new AtomicReference<>();
// 设置主内存共享变量为s1
atomicReference.set(s1);
// 比较并交换,如果现在主物理内存的值为 z3,那么交换成 l4
while (true) {
Student s2 = new Student(44, "l4");
if (atomicReference.compareAndSet(s1, s2)) {
break;
}
}
System.out.println(atomicReference.get());
}
}
class Student {
private int id;
private String name;
//。。。。
}
Atomic Arrays
Atomic array classes: AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray
Methods of the AtomicIntegerArray class:
/**
* i the index
* expect the expected value
* update the new value
*/
public final boolean compareAndSet(int i, int expect, int update) {
return compareAndSetRaw(checkedByteOffset(i), expect, update);
}
Atomic Updaters
Atomic updater classes: AtomicReferenceFieldUpdater, AtomicIntegerFieldUpdater, AtomicLongFieldUpdater
Field updaters can be used to perform atomic operations on a field of an object. They can only be used with fields declared volatile; otherwise, an exception will occur IllegalArgumentException: Must be volatile type
Common APIs:
static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> c, String fieldName): constructorabstract boolean compareAndSet(T obj, int expect, int update): CAS
public class UpdateDemo {
private volatile int field;
public static void main(String[] args) {
AtomicIntegerFieldUpdater fieldUpdater = AtomicIntegerFieldUpdater
.newUpdater(UpdateDemo.class, "field");
UpdateDemo updateDemo = new UpdateDemo();
fieldUpdater.compareAndSet(updateDemo, 0, 10);
System.out.println(updateDemo.field);//10
}
}
Atomic Accumulators
Atomic accumulator classes: LongAdder, DoubleAdder, LongAccumulator, DoubleAccumulator
Differences between LongAdder and LongAccumulator:
Similarities:
- Both the LongAdder and LongAccumulator classes use a non-blocking algorithm implemented with CAS.
- LongAdder is a special case of LongAccumulator. LongAccumulator provides more powerful functionality by allowing you to customize the accumulation rule. When
accumulatorFunctionis null, it is equivalent to LongAdder.
Differences:
- When calling
casBase, LongAccumulator computes the value usingfunction.applyAsLong(b = base, x), while LongAdder usescasBase(b = base, b + x). - LongAccumulator is more powerful. Its constructor parameters include:
accumulatorFunction, a binary operator interface that lets you specify the accumulation rule, such as addition or multiplication. It returns a computed value based on the two input parameters. LongAdder has a built-in accumulation rule.identity, the initial value of the LongAccumulator. LongAccumulator can provide a non-zero initial value, while LongAdder only provides a default value of 0.