樂觀鎖(非阻塞)指不通過鎖表來解決並發問題,一般情況下表數據都會加入一個version字段,對該字段進行比較更新來保證數據的一致性。
這里寫了個demo,應該可以說明樂觀鎖的問題。
public class TestOptimisticLock implements Runnable { private AtomicLong count = new AtomicLong(0); public void inc() { boolean updated = false; while (!updated) { Long prevCount = this.count.get(); updated = this.count.compareAndSet(prevCount, prevCount + 1); System.out.println("current thread : " + Thread.currentThread() + ";count: " + count()); } } public Long count() { return this.count.get(); } public static void main(String[] args) throws InterruptedException { TestOptimisticLock test = new TestOptimisticLock(); for(int i =0 ;i<1000;i++){ new Thread(test).start(); } Thread.sleep(2000L); System.out.println("final count : " + test.count()); } @Override public void run() { inc(); } }
機制:通過while循環,一直進行輪詢檢查是否有資格進行更新操作,並且利用AtomicLong的原子操作保證了每一次更新只有一條線程在進行操作。
