Java Reference
In-Depth Information
then the net effect of executing two transactions simultaneously will be as if they
were executed one after the other.
On the surface this sounds extremely simple, but the problem with these kinds
of transactions is that they have what is sometimes an unacceptable reduction in
performance because of how isolated transactions are implemented by the data-
base. For this reason, many applications avoid them and instead use what is
termed optimistic or pessimistic locking, which is described a bit later.
Chapter 12 looks at when to use database transactions that are isolated from
one another and how to use them with i BATIS , JDO , and Hibernate.
2.5.2
Optimistic locking
One way to handle concurrent updates is to use optimistic locking. Optimistic
locking works by having the application check whether the data it is about to
update has been changed by another transaction since it was read. One common
way to implement optimistic locking is to add a version column to each table,
which is incremented by the application each time it changes a row. Each UPDATE
statement's WHERE clause checks that the version number has not changed since it
was read. An application can determine whether the UPDATE statement succeeded
by checking the row count returned by PreparedStatement.executeUpdate() . If
the row has been updated or deleted by another transaction, the application can
roll back the transaction and start over.
It is quite easy to implement an optimistic locking mechanism in an applica-
tion that executes SQL statements directly. But it is even easier when using persis-
tence frameworks such as JDO and Hibernate because they provide optimistic
locking as a configuration option. Once it is enabled, the persistence framework
automatically generates SQL UPDATE statements that perform the version check.
Chapter 12 looks at when to use optimistic locking, explores its drawbacks, and
shows you how to use it with i BATIS , JDO , and Hibernate.
Optimistic locking derives its name from the fact it assumes that concurrent
updates are rare and that instead of preventing them the application detects and
recovers from them. An alternative approach is to use pessimistic locking, which
assumes that concurrent updates will occur and must be prevented.
2.5.3
Pessimistic locking
An alternative to optimistic locking is pessimistic locking. A transaction acquires
locks on the rows when it reads them, which prevent other transactions from
accessing the rows. The details depend on the database, and unfortunately not all
databases support pessimistic locking. If it is supported by the database, it is quite
 
 
 
 
Search WWH ::




Custom Search