Skip Headers

# Forcing a Check of the Optimistic Read Lock

Previous

Next

When you read an object with the unit of work, optimistic lock checking is not applied to that object at commit time unless you change the object. However, there are times when you want your transaction to fail if the state of an object has changed since it was read, even though you have not modified the object.

Example: Optimistic Read Lock with No Version Increment shows a transaction that updates a mortgage rate by multiplying the central bank prime rate by 1.25. The transaction forces an optimistic read lock on the central prime rate at commit time to ensure that the prime rate has not changed since the transaction began. Note that in this example, the transaction does not increment the version of the unchanged object (the central prime rate).

Optimistic Read Lock with No Version Increment

    try {
        UnitOfWork uow = session.acquireUnitOfWork();
        MortgageRate cloneMortgageRate = (MortgageRate)
          uow.registerObject(mortgageRate);
        CentralPrimeRate cloneCentralPrimeRate = (CentralPrimeRate)
          uow.registerObject(CentralPrimeRate);
        /* Change the Mortgage Rate */
        cloneMortgageRate.setRate(cloneCentralPrimeRate.getRate() * 1.25);
        /* Optimistic read lock check on Central prime rate with no version update */
        uow.forceUpdateToVersionField(cloneCentralPrimeRate, false);
        uow.commit();
    } catch(OptimisticLockException exception) {
        /* Refresh the out-of-date object */
        session.refreshObject(exception.getObject());
        /* Retry… */
    }

For another example that forces both optimistic locking and a version field update, see Example: Optimistic Read Lock with Version Increment: Service Thread in "Forcing a Version Field Update".