The lock facility allows resource adaptors to obtain transaction-based distributed locks.
In order to use the lock facility, one must obtain:
-
a reference to the
LockFacility
itself; and -
a reference to the SLEE Transaction Manager, as all locks must be obtained from within a transaction.
The following code fragment illustrates how you can obtain these references in a resource adaptor:
package ...
import javax.slee.resource.ConfigProperties;
import javax.slee.resource.ResourceAdaptor;
import javax.slee.resource.ResourceAdaptorContext;
import javax.slee.transaction.SleeTransactionManager;
import com.opencloud.rhino.facilities.lock.LockFacility;
public class FooResourceAdaptor implements ResourceAdaptor {
@Override
public void setResourceAdaptorContext(ResourceAdaptorContext context) {
// save context ref
this.context = context;
// ...
}
@Override
public void raConfigure(ConfigProperties configProps) {
// get refs to transaction manager and lock facility
txManager = context.getSleeTransactionManager();
lockFacility = (LockFacility)configProps.getProperty(LockFacility.CONFIG_PROPERTY_NAME).getValue();
// ...
}
// ...
private ResourceAdaptorContext context;
private SleeTransactionManager txManager;
private LockFacility lockFacility;
}
With these references, one can then proceed to acquire locks as necessary. For example:
private void doSomeWorkThatRequiresALock() {
// start a transaction
SleeTransaction tx = txManager.beginSleeTransaction();
try {
// acquire exclusive lock
lockFacility.acquireExclusive("SomeLock");
// do the work
// ...
// successfully completed work - commit transaction
// automatically causes the lock to be released
tx = null;
txManager.commit();
}
catch (Exception e) {
if (tx != null) {
// failed to complete work - rollback transaction
// automatically causes the lock to be released
tx.rollback();
}
}
}