Java Reference
In-Depth Information
Table 8-3. Lock Modes
Mode
Description
NONE
Reads from the database only if the object is not available from the caches.
READ
Reads from the database regardless of the contents of the caches.
UPGRADE
Obtains a dialect-specific upgrade lock for the data to be accessed (if this is
available from your database).
UPGRADE_NOWAIT
Behaves like UPGRADE , but when support is available from the database and
dialect, the method will fail with a locking exception immediately. Without this
option, or on databases for which it is not supported, the query must wait for
a lock to be granted (or for a timeout to occur).
An additional lock mode, WRITE , is acquired by Hibernate automatically when it has writ-
ten to a row within the current transaction. This mode cannot be set explicitly, but calls to
getLockMode may return it.
Having discussed locking in general, we need to touch on some of the problems that locks
can cause.
Deadlocks
Even if you have not encountered a deadlock (sometimes given the rather louche name of
“deadly embrace”) in databases, you have probably encountered the problem in multithreaded
Java code. The problem arises from similar origins.
Two threads of execution can get into a situation in which each is waiting for the other
to release a resource that it needs. The most common way to create this situation in a data-
base is shown in Figure 8-2.
Each thread obtains a lock on its table when the update begins. Each thread proceeds
until the table held by the other user is required. Neither thread can release the lock on its
own table until the transaction completes—so something has to give.
A deadlock can also occur when a single thread of execution is carrying out an equivalent
sequence of operations using two Session objects connected to the same database. In prac-
tice, the multiple-thread scenario is more common.
Fortunately, a database management system (DBMS) can detect this situation automati-
cally, at which point the transaction of one or more of the offending processes will be aborted
by the database. The resulting deadlock error will be received and handled by Hibernate as a
normal HibernateException . Now you must roll back your transaction, close the session, and
then (optionally) try again.
Listing 8-3 demonstrates how four updates from a pair of sessions can cause a deadlock.
If you look at the output from the threads, you will see that one of them completes while the
other fails with a deadlock error.
n Caution The HSQL database does not support sufficient levels of isolation to run this example—you
will never get a deadlock, and you will get inconsistent data. If you want to see the deadlock in action,
you will need to use a more sophisticated database product (e.g., PostgreSQL).
You should also be aware that if you want to run the test using the MySQL database, you must use
MySQLInnoDBDialect to ensure that the appropriate level of transactions is supported.
Search WWH ::




Custom Search