Java Reference
In-Depth Information
which could prevent other users from accessing them. Consequently, a much bet-
ter approach is to use a separate database transaction for each request.
Using offline locking
When using a separate database transaction for each request, the business logic
for the Acknowledge Order use case uses one transaction to retrieve the order
and another transaction to update the order. The trouble with this approach is
that neither serializable transactions nor pessimistic locking work across multiple
transactions. Database-level pessimistic locking cannot be used across a series of
transactions because the database releases locks at the end of the each transac-
tion. Similarly, serializable transactions only handle concurrent updates made
during their execution because of how they are implemented by the database.
Moreover, optimistic locking only works, by default, within a single transaction
because Hibernate or JDO only checks objects updated during the transaction.
Consequently, the application must handle concurrent updates across a sequence
of transactions using a different approach.
There are a couple of different mechanisms that an application can use. One
option is the Pessimistic Offline Lock pattern, which implements an application-
level locking mechanism that locks data across multiple database transactions (see
section 13.5). The other option is the Optimistic Offline Lock pattern, which
extends optimistic locking to work across a sequence of database transactions.
Whereas regular optimistic locking only detects data that has changed since it was
read earlier within the same database transaction, optimistic offline locking deter-
mines whether data has changed since the start of the use case, which might have
been several database transactions ago. Let's look at how this pattern works.
13.2 Overview of the Optimistic Offline Lock pattern
This pattern detects concurrent updates in the same way as the optimistic locking
mechanism described in the previous chapter. When updating the database, it
checks that the data is unchanged since it was read. The only difference is that the
data is read and updated in two separate transactions. The most common way to
implement the Optimistic Offline Lock pattern is for the application to use a ver-
sion number to detect when a row that was read in a previous transaction has
been changed. When the application reads a row from the database, it stores the
row's version number as part of the session state, for example, in the HttpSession .
Then, when updating a row the application compares its current version number
to the one stored in the session state. If they are different, the application does
 
 
 
 
 
Search WWH ::




Custom Search