Java中的java.util.concurrent.atomic
包提供了多種原子操作工具類,以下是核心類及其方法:
?1. AtomicBoolean?
?方法?:
get()
:獲取當前值set(boolean newValue)
:強制設置值compareAndSet(boolean expect, boolean update)
:CAS操作getAndSet(boolean newValue)
:原子獲取舊值并設置新值lazySet(boolean newValue)
:最終一致性設置(不保證立即可見)
?2. AtomicInteger/AtomicLong?
?方法?:
get()
/intValue()
:獲取當前值set(int newValue)
:強制設置值compareAndSet(int expect, int update)
:CAS操作getAndIncrement()
:原子自增(返回舊值)getAndDecrement()
:原子自減getAndAdd(int delta)
:原子加法incrementAndGet()
:自增并返回新值updateAndGet(IntUnaryOperator updateFunction)
:函數式更新
?3. AtomicReference<V>?
?方法?:
get()
:獲取引用值set(V newValue)
:強制設置引用compareAndSet(V expect, V update)
:CAS操作getAndSet(V newValue)
:原子交換引用updateAndGet(UnaryOperator<V> updateFunction)
:函數式更新引用
?4. AtomicIntegerArray/AtomicLongArray?
?方法?:
length()
:數組長度get(int i)
:獲取下標i
的值set(int i, int newValue)
:設置指定下標值compareAndSet(int i, int expect, int update)
:CAS操作指定元素getAndIncrement(int i)
:原子自增數組元素
?5. AtomicStampedReference<V>?
?方法?:
getReference()
:獲取引用值getStamp()
:獲取版本戳compareAndSet(V expectedReference, V newReference, int expectedStamp, int newStamp)
:帶版本戳的CAS
?6. AtomicMarkableReference<V>?
?方法?:
isMarked()
:獲取標記狀態compareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark)
:帶標記位的CAS
?7. LongAdder/DoubleAdder(高并發統計場景)?
?方法?:
add(long x)
:累加值sum()
:返回總和(非原子)reset()
:重置計數器
?特點總結?:
- ?線程安全?:所有操作均為原子性
- ?無鎖設計?:基于CAS實現高性能并發
- ?內存語義?:遵循
volatile
的可見性和有序性 - ?函數式支持?:JDK8+提供
updateAndGet
等函數式方法
適用于計數器、狀態標志、對象引用更新等場景。