1.乐观锁
当处理对象状态时为了防止冲突
例:一个下订单的状态status
a.更新status为1购买,b取得status为1,这时a要退货把status改为2.
这时如果b还按1的状态去处理,发货了。就出错了。
正确的做法为:
当b发货时,为了处理并发脏读,需要先根据原status状态去更新status为3订单处理中
int res = update status = 3 from order r where r.status = 1 and r.orderId = xx
当res更新到状态大于0时,就可以发货,发货完了,再修改status为4已发货。
当res等于0时说明a已经修改订单状态。
而a要修改状态为2退货时
int res = update status = 2 from order r where r.status = 1 and r.orderId = xx
如果更新结果res小于0,说明b已修改状态已进行发货处理,不能执行退货。
这个处理并发脏读的方式就是乐观锁。
2.悲观锁
oracle悲观锁分为等待for update,不等待for update nowait
等待型
select * from order r where r.orderId = xx for update;
一个执行没有commit时另一个只能等待。
不等待型
select * from order r where r.orderId = xx for update nowait;
一个执行没有commit时另一个直接报异常。
select * from order r where r.orderId = xx for update nowait t;
一个执行没有commit时另一个等待t秒报异常。