Java併發程式設計(十一)Java中的原子操作類
阿新 • • 發佈:2018-12-04
一、原子操作類簡介
JDK1.5開始提供了java.util.concurrent.atomic包,其中有一系列用法簡單、效能高效、可以執行緒安全更新變數的原子操作類,目前(JDK1.7)大概有這麼些:
二、原子操作類實現原理
以AtomicInteger為例看下原始碼,其中的兩個方法getAndSet,getAndIncrement,都是無限迴圈呼叫compareAndSet,直到成功,CAS方法呼叫的是unsafe的方法,目前unsafe限制越來越嚴,也不建議程式設計師使用了,這裡不做分析。原始碼如下:
public class AtomicInteger extends Number implements java.io.Serializable { /** * Atomically sets to the given value and returns the old value. * * @param newValue the new value * @return the previous value */ public final int getAndSet(int newValue) { for (;;) { int current = get(); if (compareAndSet(current, newValue)) return current; } } /** * Atomically increments by one the current value. * * @return the previous value */ public final int getAndIncrement() { for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return current; } } /** * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } }