事务隔离通常是通过给事务中访问的资源加锁来实现的。在多用户并发读写同一个数据资源的情况下如果不加任何控制,资源的统一性将会被破坏。
举个火车票售票的栗子(不加并发控制的情况):
有两个旅客同时使用手机售票APP购买同一趟列车的车票。两人同时下单购买,售票系统后台同时(并发)接收到两个购票请求(对应两个事务),都会先查询余票,由于是并发请求,所以两次余票查询结果的相同,这里假设查询结果的余票数量为20
;然后售票系统开始对这两个事务进行处理:分别将系统中的余票数量修改为20-1=19
并写回数据库。这样一来,就导致了实际售出2
张车票,但是售票系统中的余票数量却只减少了1
张。这就是缺少并发控制带来的问题。
乐观锁(Optimistic Locking)和悲观锁(Pessimistic Locking)是并发控制主要采用的两种技术手段。
相关概念
悲观锁(Pessimistic Locking)
悲观锁假定会发生并发冲突,屏蔽一切可能违反数据完整性的操作。也就是说,悲观锁对数据在并发的情况下被外界修改
悲观锁主要用于资源并发访问冲突激烈的情况
乐观锁(Optimistic Locking)
悲观锁假定不会发生并发冲突,只在提交操作时检查是否违反数据完整性。
Transactional isolation is usually implemented by locking whatever is accessed in a transaction. There are two different approaches to transactional locking: Pessimistic locking and optimistic locking.
The disadvantage of pessimistic locking is that a resource is locked from the time it is first accessed in a transaction until the transaction is finished, making it inaccessible to other transactions during that time. If most transactions simply look at the resource and never change it, an exclusive lock may be overkill as it may cause lock contention, and optimistic locking may be a better approach. With pessimistic locking, locks are applied in a fail-safe way. In the banking application example, an account is locked as soon as it is accessed in a transaction. Attempts to use the account in other transactions while it is locked will either result in the other process being delayed until the account lock is released, or that the process transaction will be rolled back. The lock exists until the transaction has either been committed or rolled back.
Java中的悲观锁和乐观锁
——————–【参考文章】——————–