 |
| Why Optimistic Lock(OL)? |
|
variable 原创 更新:2008-04-02 12:44:16 版本: 1.0
|
|
Why Optimistic Lock(OL)?
什么是 OL?就是在应用程序中对同时数据更新进行处理和控制,而非全部依赖 或委托数据库系统来处理。(To handle concurrent update to data in applications, rather than totally (depends) delegates to database systems)。
它实现起来很简单,一般在数据表中设一字段(column)作为标识用途,其数据 类型多为时间或序列数等。每次应用程序对行数据进行更新时,要一并提取该字 段;到执行更新前,应用程序负责检查该字段,是否与当前数据库的数据相等。 若相等,则可以进行更新,并在更新数据时,将该字段也一并更新;若不相符, 则说明别的线程或业务(transaction)已经更新了该数据。这种情况下,则可根 据业务要求,提醒用户该数据已被别人更新云云。
嚯!有点儿费劲儿。
There's another term called "Pessimistic Lock", which uses object locks from database for concurrent control to data access. For example, row level locks and table level locks etc. When you append "for update" to your select query, it actually acquires row level locks on the data your selection will get. This means other "concurrent" transactions can only read the data your selection locks, but cannot update and/or delete.
"Pessimistic Lock" seems simpler but it can introduce deadlock and thus is not a good alternative.
Database transactions can only ensure data integrity. It cannot prevent "silent update" in that one update has been wipped out (overwritten) by a later update. Think about a bank account credit case if you cannot get the picture.
Optimistic Lock solves this problem easily without high risk of deadlock.
Speaking of transaction, most relational database systems would start transaction automatically, in that every statement, no matter it's selection, deletion, update or insertion, is treated as a transaction. If you want to include multiple statement in one transaction, you need to set off this behavior. That's what the java.sql.Connection.setAutoCommit(boolean) used for. If you set it off, you must manually commit the transaction by calling the commit() method. If transaction failed, you wanna call rollback() to handle the situation.
|
|
|
评论人:javamonkey
|
发表时间: Sun Apr 06 11:51:46 CST 2008
|
EJB,Hibernate都有自己的实现
也可以参考Enterprise pattern 来了解 Optimistic Lock
|
|
|
|
|
 |