Show TOC Start of Content Area

This graphic is explained in the accompanying text Locking  Locate the document in its SAP Library structure

Use

The concept of locking is used to ensure the integrity of data being modified in a transaction. The SAP JDO implementation uses the locking concept to set locks on the underlying database tables or individual table rows, and not on the JDO instances themselves.

Activities

The SAP JDO API enables you to manage locks programmatically in the application code.

The locking functions are provided by the com.sap.jdo.Locking interface. To get a reference to this interface, you must invoke the getLocking() method of com.sap.jdo.SAPJDOHelper. You can then acquire and release locks using the methods of the Locking interface:

This graphic is explained in the accompanying text

import com.sap.jdo.Locking;

import com.sap.jdo.SAPJDOHelper;

...

public void changeDepartmentName(int depId, String newName) {

      pm = null;

      try {

         pm = pmf.getPersistenceManager();

         Transaction tx = pm.currentTransaction();

         tx.setOptimistic(false);

         Locking locking = SAPJDOHelper.getLocking();

         tx.begin();

         Department department =

            (Department) pm.getObjectById(new Department.Id(depId), false);

         try {

            locking.lock(

               Locking.LIFETIME_TRANSACTION,

               pm,

               department,

               Locking.MODE_EXCLUSIVE_CUMULATIVE);

         } catch (Exception e) {

            e.printStackTrace();

         }

         department.setName(newName);

         tx.commit();

 

      } finally {

         if (pm != null && !pm.isClosed()) {

            if (pm.currentTransaction().isActive())

               pm.currentTransaction().rollback();

            pm.close();

      }

   }

}

 

The parameter lifetime defines the validity period of the lock. You can use Locking.LIFETIME_TRANSACTION to lock the data until the end of the transaction, or Locking.LIFETIME_USERSESSION for a lock that is valid until the end of the user session. The locks are automatically released after the end of the specified validity period.

The locking mode may be one of the following:

·        Locking.MODE_SHARED – a shared lock implies that several transactions can lock the data simultaneously for read operations

·        Locking.MODE_EXCLUSIVE_CUMULATIVE – an exclusive lock is imposed by a single transaction that modifies the data; a cumulative lock can be reused multiple times by the same transaction.

·        Locking.MODE_EXCLUSIVE_NONCUMULATIVE – the lock cannot be used again in the same transaction.

In addition, you can use Locking.WILDCARD_CHARACTER_SINGLE and Locking.WILDCARD_CHARACTER_MULTI characters, which enable you to lock generic areas in primary key columns of JDBC type VARCHAR.

 

See also:

Locks

 

End of Content Area