五分钟学会悲观乐观锁-java vs mysql vs redis三种实现

  • 2019 年 10 月 3 日
  • 筆記

1 悲观锁乐观锁简介

乐观锁( Optimistic Locking ) 相对悲观锁而言,乐观锁假设认为数据一般情况下不会造成冲突,所以在数据进行提交更新的时候,才会正式对数据的冲突与否进行检测,如果发现冲突了,则让返回用户错误的信息,让用户决定如何去做。

悲观锁,正如其名,它指的是对数据被外界(包括本系统当前的其他事务,以及来自外部系统的事务处理)修改持保守态度,因此,在整个数据处理过程中,将数据处于锁定状态。(百科)

最形象的悲观锁 vs 乐观锁

五分钟学会悲观乐观锁-java  vs mysql vs redis三种实现

 

2.悲观锁乐观锁使用场景

两种锁各有优缺点,不能单纯的定义哪个好于哪个。乐观锁比较适合数据修改比较少,读取比较频繁的场景,即使出现了少量的冲突,这样也省去了大量的锁的开销,故而提高了系统的吞吐量。但是如果经常发生冲突(写数据比较多的情况下),上层应用不不断的retry,这样反而降低了性能,对于这种情况使用悲观锁就更合适。

3.Java中悲观乐观锁实现

乐观锁:java中的乐观锁基本都是通过CAS操作实现的,CAS是一种更新的原子操作,比较当前值跟传入值是否一样,一样则更新,否则失败。以 java.util.concurrent 中的 AtomicInteger 为例,该类中原子操作保证了线程访问的准确性。

getAndIncrement():获取数据

import java.util.concurrent.atomic.AtomicInteger;  public class JavaAtomic {   public static void main(String[] args) throws InterruptedException {   ProcessingThread pt = new ProcessingThread();   Thread t1 = new Thread(pt, "t1");   t1.start();   Thread t2 = new Thread(pt, "t2");   t2.start();   t1.join();   t2.join();   System.out.println("Processing count=" + pt.getCount());   }  }  class ProcessingThread implements Runnable {   private AtomicInteger count = new AtomicInteger();   @Override   public void run() {   for (int i = 1; i < 5; i++) {   processSomething(i);   count.incrementAndGet();   }   }   public int getCount() {   return this.count.get();   }   private void processSomething(int i) {   // processing some job   try {   Thread.sleep(i * 1000);   } catch (InterruptedException e) {   e.printStackTrace();   }   }  }

 

compareAndSet(int expect, int update): 更新数据

import java.util.concurrent.atomic.AtomicInteger;    public class Main  {   public static void main(String[] args)   {   AtomicInteger atomicInteger = new AtomicInteger(100);     boolean isSuccess = atomicInteger.compareAndSet(100,110); //current value 100     System.out.println(isSuccess); //true     isSuccess = atomicInteger.compareAndSet(100,120); //current value 110     System.out.println(isSuccess); //false     }  }

 

利用JNI(Java Native Interface)来完成CPU指令的操作,访问寄存器内存数据进行数据访问和设置

悲观锁:java中的悲观锁就是Synchronized,如单例模式所示

public class SingletonDemo {   private static SingletonDemo instance = null;     private SingletonDemo() { }     public static synchronized SingletonDemo getInstance() {   if (instance == null) {   instance = new SingletonDemo ();   }   return instance;   }  }

 

乐观锁+悲观锁:AQS框架下的锁则是先尝试cas乐观锁去获取锁,获取不到,才会转换为悲观锁,如RetreenLock【http://ifeve.com/reentrantlock-and-fairness/】

public class ReentrantLockTest {      private static Lock fairLock = new ReentrantLock(true);      private static Lock unfairLock = new ReentrantLock();      @Test      public void fair() {          System.out.println("fair version");          for (int i = 0; i < 5; i++) {              Thread thread = new Thread(new Job(fairLock));              thread.setName("" + i);              thread.start();          }          try {              Thread.sleep(5000);          } catch (InterruptedException e) {              e.printStackTrace();          }      }      @Test      public void unfair() {          System.out.println("unfair version");          for (int i = 0; i < 5; i++) {              Thread thread = new Thread(new Job(unfairLock));              thread.setName("" + i);              thread.start();          }          try {              Thread.sleep(5000);          } catch (InterruptedException e) {              e.printStackTrace();          }      }      private static class Job implements Runnable {          private Lock lock;          public Job(Lock lock) {              this.lock = lock;          }          @Override          public void run() {              for (int i = 0; i < 5; i++) {                  lock.lock();                  try {                      System.out.println("Lock by:"                              + Thread.currentThread().getName());                  } finally {                      lock.unlock();                  }              }          }      }  }

 

4 数据库悲观锁乐观锁的实现(以mysql为例)

悲观锁,使用事务实现

//0.开始事务  begin;/begin work;/start transaction; (三者选一就可以)  //1.查询出商品信息  select status from t_goods where id=1 for update;  //2.根据商品信息生成订单  insert into t_orders (id,goods_id) values (null,1);  //3.修改商品status为2  update t_goods set status=2;  //4.提交事务  commit;/commit work;

 

乐观锁

1.使用数据版本(Version)记录机制实现

五分钟学会悲观乐观锁-java  vs mysql vs redis三种实现

 

2.乐观锁定的第二种实现方式和第一种差不多,同样是在需要乐观锁控制的table中增加一个字段,名称无所谓,字段类型使用时间戳(timestamp), 和上面的version类似

5 nosql 悲观锁乐观锁的实现(以redis为例)

乐观锁使用watch

五分钟学会悲观乐观锁-java  vs mysql vs redis三种实现

 

悲观锁使用事务

> MULTI  OK  > INCR foo  QUEUED  > INCR bar  QUEUED  > EXEC  1) (integer) 1  2) (integer) 1

 

6 总结

乐观锁机制采取了更加宽松的加锁机制。悲观锁大多数情况下依靠数据库的锁机制实现,以保证操作最大程度的独占性。但随之而来的就是数据库 性能的大量开销,特别是对长事务而言,这样的开销往往无法承受。相对悲观锁而言,乐观锁更倾向于开发运用。【百科】

参考资料

【1】https://chenzhou123520.iteye.com/blog/1860954

【2】https://chenzhou123520.iteye.com/blog/1863407

【3】https://blog.csdn.net/skycnlr/article/details/85689582

【4】https://www.journaldev.com/1095/atomicinteger-java

【5】https://howtodoinjava.com/java/multi-threading/atomicinteger-example/

【6】https://developpaper.com/transaction-mechanism-and-optimistic-lock-implementation-in-redis/