Java Reference
In-Depth Information
Using a lock manager
The simplest way to use a lock manager is for the database transaction that reads
the data to first lock the data before reading it. This ensures that the data that is
read is up to date because once it is locked no other transactions can update it.
You can do this if, for example, you are loading an object by its primary key
because the transaction can call the lock manager before calling the repository or
persistence framework API . However, if a transaction obtains the object by execut-
ing a query or by navigation, it does not know the object's primary key until after
it has been loaded. It is possible that in between the transaction loading the object
and locking it another transaction changes the object, which causes the first trans-
action to use stale data and potentially overwrite those changes. To see why, con-
sider the scenario shown in figure 13.5, which shows two database transactions
accessing the same data. In this example, transaction A reads the data at the start
of one use case and transaction B updates the data at the end of another use case.
In this scenario, transaction A reads an order that is locked by transaction B.
Transaction B then updates the order and releases the lock, which enables trans-
action A to acquire it. As a result, transaction A has stale data and would subse-
quently overwrite the changes made by transaction B.
One solution to this problem is to use database-level pessimistic locking and pre-
vent another transaction from changing the data before the lock is claimed. In the
scenario in figure 13.5, transaction A would claim the database-level pessimistic
lock, which would block B from updating it and releasing the offline lock. Trans-
action A would then discover that the order had an offline lock and would roll back.
Database transaction A
Database transaction B
Begin transaction
Read order
Begin transaction
Update order
Release lock
Commit transaction
Claim lock
Returns order (which is now out
of date)
Commit transaction
Figure 13.5
An example of reading before locking
Time
 
Search WWH ::




Custom Search