1. 悲观方法:
悲观方法是一种并发控制算法方法,其中如果在将来的某个时间点彼此发生冲突,则事务会延迟。它锁定数据库的记录以进行更新访问,其他用户只能以只读方式访问记录或必须等待记录被“解锁”。由于死锁的风险,使用悲观并发方法对应用程序进行编程可能会更加复杂和复杂。
在悲观方法的执行中,首先执行验证操作,如果验证与锁的兼容性一致,则只执行读取、计算和写入操作,即,
Validate -> Read -> Compute -> Write
在悲观方法中,我们使用两种常见的锁定协议:
- 两阶段锁定协议
- 时间戳排序协议
2. 乐观态度:
乐观方法是一种基于数据库操作冲突很少的假设的并发控制算法方法。建议将这些事务运行到完成并仅在它们提交之前检查冲突,并且在执行事务时不进行检查。这种方法不需要任何锁定或时间戳方法。在乐观方法中,事务的执行没有任何限制问题,直到事务提交。乐观方法允许事务以不同步的方式进行,并且还允许在最后进行冲突检查。这种方法也称为验证或认证方法。
在乐观执行期间,我们只进行读取和计算操作而不进行验证,并在正确的操作之前验证交易。
Read -> Compute -> Validate -> Write
乐观方法的优点:
- 在乐观方法事务中,当联系人在那里时回滚变得非常容易。
- 在乐观的方法中,您不会发现任何级联回滚,因为它仅使用数据的本地副本而不是数据库。
乐观方法的缺点:
- 使用乐观方法进行并发控制可能非常昂贵,因为它需要回滚。
- 如果在这种方法中大事务和小事务之间存在冲突,那么只有大事务会重复回滚,因为它们包含更多的冲突。
悲观法和乐观法的区别:
Pessimistic Approach |
Optimistic Approach |
It locks records so that selected record for update will not be changed meantime by another user | It doesn’t lock the records as it ensures record wasn’t changed in time between SELECT & SUBMIT operations. |
The conflicts between transactions are very large in this approach | The conflicts between transactions are less as compared to pessimistic approach. |
The synchronization of transactions is conducted in start phase of life cycle of execution of a transaction | The synchronization of transactions is conducted in later phase or gets delayed in execution of a transaction |
It is simple in designing and in programming. | It is more complex in designing and managing deadlocks’ risk |
It has a higher storage cost | It has a relatively lower storage cost as compared to pessimistic approach |
It has a lower degree of concurrency | It has a high degree of concurrency |
This approach is found to use where there are more transaction conflicts | This approach is found to use where there are fewer transaction conflicts or very rare |
The flow of transaction phases: Validate -> Read -> Compute -> Write |
The flow of transaction phases: Read -> Compute -> Validate -> Write |
It helps in protecting the system from the concurrency conflict | It allows the conflict to happen |
It is suitable for a small database or a table which has less records | It is suitable for a large database or has more records |