AtomicInteger來研究在沒有鎖的情況下是如何做到數據正確性的?
這裏舉例說明一個方法:getAndIncrement
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
這裏面有個compareAndSet方法,其實是JNI調用,
在這裏採用了CAS操作,每次從內存中讀取數據然後將此數據和+1後的結果進行CAS操作,如果成功就返回結果,否則重試直到成功爲止。
而compareAndSet利用JNI來完成CPU指令的操作。