乐观锁(非阻塞)指不通过锁表来解决并发问题,一般情况下表数据都会加入一个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的原子操作保证了每一次更新只有一条线程在进行操作。