Skip Headers

# Pessimistic Locking Policy

Previous

Next

With pessimistic locking, the first user who accesses the data with the purpose of updating it locks the data until completing the update.

When using a pessimistic locking policy, you can configure the policy to either fail immediately or to wait until the read lock is acquired.

You can use a pessimistic locking policy only in a project with a container-managed persistence type (see "Configuring Persistence Type") and with descriptors that have EJB information (see "Configuring a Descriptor With EJB Information").

You can also use pessimistic locking (but not a pessimistic locking policy) at the query level (see "Configuring Named Query Options").

TopLink provides an optimization for pessimistic locking when this locking is used with entity beans with container-managed persistence: if you set your query to pessimistic locking and run the query in its own new transaction (which will end after the execution of the finder), then TopLink overrides the locking setting and does not append `FOR UPDATE` to the SQL. However, the use of this optimization may produce an undesirable result if the pessimistic lock query has been customized by the user with a SQL string that includes FOR UPDATE. In this case, if the conditions for the optimization are present, the query will be reset to nonpessimistic locking, but the SQL will remain the same resulting in the locking setting of the query conflicting with the query's SQL string. To avoid this problem, you can take one of the following two approaches:

- Use EJB QL or a TopLink's expression (see Understanding TopLink Expressions) for the selection criteria. This will give TopLink control over the SQL generation.

- Place the finder in a transaction to eliminate conditions for the optimization.