樂觀鎖(Optimistic Lock)


樂觀鎖(非阻塞)指不通過鎖表來解決並發問題,一般情況下表數據都會加入一個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的原子操作保證了每一次更新只有一條線程在進行操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM