package com.renxo.cms.util; import java.io.Serializable; import java.util.concurrent.locks.Lock; import org.jgroups.JChannel; import org.jgroups.blocks.locking.LockService; /** * A LockManager implementation for distributed environments based * on JGroups' {@link LockService}. * * @param * the type of the lock key. */ public class DistributedJGroupsLockManager extends AbstractJdkLockManager { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final long DEFAULT_TRY_LOCK_TIMEOUT = 5 * 1000L; // ---------------------------------------------------------------------- // Fields // ---------------------------------------------------------------------- private String configurationFile; private String locksGroupsName = "locks"; private JChannel jChannel; private LockService lockService; // ---------------------------------------------------------------------- // Setters for IoC // ---------------------------------------------------------------------- /** * Sets the JGroups configuration file to use. A locking protocol should be * configured towards the top of the stack. * * @param configurationFile * the JGroups configuration file to set. * @see LockService */ public void setConfigurationFile(String configurationFile) { this.configurationFile = configurationFile; } /** * Configures the locks group name. This will be used as the JChannel * cluster name. Default is locks. * * @param locksGroupsName * the locks group name to set. */ public void setLocksGroupsName(String locksGroupsName) { this.locksGroupsName = locksGroupsName; } // ---------------------------------------------------------------------- // AbstractJdkLockManager implementations // ---------------------------------------------------------------------- @Override protected Lock getLock(K key) { return lockService.getLock(String.valueOf(key)); } @Override protected long defaultTryLockTimeout() { return DEFAULT_TRY_LOCK_TIMEOUT; } // ---------------------------------------------------------------------- // Lifecycle methods // ---------------------------------------------------------------------- /** * Initializes the JChannel. * * @throws Exception * if the JChannel cannot be initialized. */ public void init() throws Exception { jChannel = new JChannel(configurationFile); jChannel.connect(locksGroupsName); lockService = new LockService(jChannel); } /** * Shuts down the JChannel. */ public void shutdown() { if (jChannel != null && jChannel.isConnected()) { jChannel.close(); } } }