[.net programming language only]

Implementing exception handling in locking scenarios for .NET applications

To prevent locks from being held for excessive amounts of time when a LockTimeoutException exception or a LockDeadlockException exception occurs, your application must catch unexpected exceptions and call the rollback method when an unexpected event occurs.

Procedure

  1. Catch the exception, and display resulting message.
    try {
    ...
    } catch (GridException ge) {
       System.Console.WriteLine(ge.ToString());
    }

    When a LockDeadlockException exception is thrown, it might be contained as an inner exception within another exception. The previous code snippet displays the top-level exception with the entire inner exception chain, if present. The exception message specific to the LockDeadlockException exception contains details about the lock conflict. For more information about how to interpret this message, see Troubleshooting deadlocks.

    IBM.WebSphere.Caching.Map.LockDeadlockException: Message
    This message represents the string that is passed as a parameter when the exception is created and thrown.
  2. Roll back the transaction after an exception:
    IGridMapPessimisticTx<String,Person> ptmap; 
    ptmap = grid.GetGridMapPessimisticTx<String,Person>(“PERSON”); 
    try { 
       ptmap.Transaction.Begin(); 
       Person p = ptmap.Get("Lynn"); 
       // Lynn had a birthday, so we make her 1 year older. 
       p.Age++; 
       ptmap.Put(p.name, p); 
       ptmap.Transaction.Commit(); 
    } 
    catch (GridException ge) { 
       System.Console.WriteLine(ge.ToString()); 
    } 
    finally { 
       if ( ptmap.Transaction.Active ) 
          ptmap.Transaction.Rollback(); 
    }
    The finally block in the snippet of code ensures that a transaction is rolled back when an unexpected exception occurs. It not only handles a LockDeadlockException exception, but any other unexpected exception that might occur. The finally block handles the case where an exception occurs during a commit method invocation. This example is not the only way to deal with unexpected exceptions, and there might be cases where an application wants to catch some of the unexpected exceptions that can occur and display one of its application exceptions. You can add catch blocks as appropriate, but the application must ensure that the snippet of code does not exit without completing the transaction.