Java Code Examples for org.apache.curator.framework.recipes.locks.InterProcessMutex#release()

The following examples show how to use org.apache.curator.framework.recipes.locks.InterProcessMutex#release() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateKeyspacesCommand.java    From emodb with Apache License 2.0 6 votes vote down vote up
private static void inMutex(CuratorFramework curator, String mutexPath, Runnable work) {
    final InterProcessMutex mutex = new InterProcessMutex(curator, mutexPath);
    try {
        // try to acquire mutex for index within flush period
        if (mutex.acquire(LOCK_ACQUIRE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) {
            try {
                work.run();
            } finally {
                mutex.release();
            }
        } else {
            _log.warn("could not acquire index lock after {} millis!!", LOCK_ACQUIRE_TIMEOUT.toMillis());
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 2
Source File: ZooLockAspect.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 环绕操作
 *
 * @param point 切入点
 * @return 原方法返回值
 * @throws Throwable 异常信息
 */
@Around("doLock()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    Object[] args = point.getArgs();
    ZooLock zooLock = method.getAnnotation(ZooLock.class);
    if (StrUtil.isBlank(zooLock.key())) {
        throw new RuntimeException("分布式锁键不能为空");
    }
    String lockKey = buildLockKey(zooLock, method, args);
    InterProcessMutex lock = new InterProcessMutex(zkClient, lockKey);
    try {
        // 假设上锁成功,以后拿到的都是 false
        if (lock.acquire(zooLock.timeout(), zooLock.timeUnit())) {
            return point.proceed();
        } else {
            throw new RuntimeException("请勿重复提交");
        }
    } finally {
        lock.release();
    }
}
 
Example 3
Source File: SpringBootDemoZookeeperApplicationTests.java    From spring-boot-demo with MIT License 6 votes vote down vote up
public void manualBuy() {
    String lockPath = "/buy";
    log.info("try to buy sth.");
    try {
        InterProcessMutex lock = new InterProcessMutex(zkClient, lockPath);
        try {
            if (lock.acquire(1, TimeUnit.MINUTES)) {
                doBuy();
                log.info("buy successfully!");
            }
        } finally {
            lock.release();
        }
    } catch (Exception e) {
        log.error("zk error");
    }
}
 
Example 4
Source File: ZkDistributedLock.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * 解锁
 * 注意:1、加锁和解锁必须配对地调用!
 * 2、解锁线程必须与加锁线程是同一个,即不支持那种异步回调解锁!
 *
 * @return true if unlock successfully otherwise false. We don't care how the unlock fails.
 */
public static boolean unlock(int innerId) {
    InterProcessMutex mutex = map.remove(innerId);
    if (mutex != null) {
        if (mutex.isAcquiredInThisProcess()) {
            try {
                mutex.release();
                LOG.debug("解锁成功...");
                return true;
            } catch (Exception e) {
                LOG.error("解锁失败!", e);
                return false;
            }
        } else {
            LOG.error(new LockNotOwnedByCurrentThread());
            return false;
        }
    } else {
        //这里暂时不抛出异常,只打印日志
        LOG.error(new RuntimeException("API误用,根本不存在锁,你解什么锁?"));
        return false;
    }
}
 
Example 5
Source File: ZooLockAspect.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 环绕操作
 *
 * @param point 切入点
 * @return 原方法返回值
 * @throws Throwable 异常信息
 */
@Around("doLock()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    Object[] args = point.getArgs();
    ZooLock zooLock = method.getAnnotation(ZooLock.class);
    if (StrUtil.isBlank(zooLock.key())) {
        throw new RuntimeException("分布式锁键不能为空");
    }
    String lockKey = buildLockKey(zooLock, method, args);
    InterProcessMutex lock = new InterProcessMutex(zkClient, lockKey);
    try {
        // 假设上锁成功,以后拿到的都是 false
        if (lock.acquire(zooLock.timeout(), zooLock.timeUnit())) {
            return point.proceed();
        } else {
            throw new RuntimeException("请勿重复提交");
        }
    } finally {
        lock.release();
    }
}
 
Example 6
Source File: JobRunningZKStateManager.java    From Eagle with Apache License 2.0 6 votes vote down vote up
@Override
public void truncateEverything() {
	String path = zkRoot;
	InterProcessMutex lock = new InterProcessMutex(_curator, path);
	try{
		lock.acquire();
		if(_curator.checkExists().forPath(path) != null){
			_curator.delete().deletingChildrenIfNeeded().forPath(path);
		}
	}catch(Exception ex){
		LOG.error("fail truncating verything", ex);
		throw new RuntimeException(ex);
	}
	finally {
       	try{
       		lock.release();
       	}catch(Exception e){
       		LOG.error("fail releasing lock", e);
       		throw new RuntimeException(e);
       	}
	}
}
 
Example 7
Source File: DataHostSwitch.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
public static boolean switchWithZK(int id, PhysicalDataHost dh, String subHostName, ManagerConnection mc) {
    CuratorFramework zkConn = ZKUtils.getConnection();
    InterProcessMutex distributeLock = new InterProcessMutex(zkConn, KVPathUtil.getHaLockPath(dh.getHostName()));
    try {
        try {
            if (!distributeLock.acquire(100, TimeUnit.MILLISECONDS)) {
                mc.writeErrMessage(ErrorCode.ER_YES, "Other instance is change the dataHost status");
                return false;
            }
            String result = dh.switchMaster(subHostName, false);
            DataHostDisable.setStatusToZK(KVPathUtil.getHaStatusPath(dh.getHostName()), zkConn, result);
            HaConfigManager.getInstance().haFinish(id, null, result);
        } finally {
            distributeLock.release();
            LOGGER.info("reload config: release distributeLock " + KVPathUtil.getConfChangeLockPath() + " from zk");
        }
    } catch (Exception e) {
        LOGGER.info("reload config using ZK failure", e);
        mc.writeErrMessage(ErrorCode.ER_YES, e.getMessage());
        HaConfigManager.getInstance().haFinish(id, e.getMessage(), null);
        return false;
    }
    return true;
}
 
Example 8
Source File: ZKClientImpl.java    From codes-scratch-zookeeper-netty with Apache License 2.0 6 votes vote down vote up
/**
 * 使用分布式锁执行任务
 *
 * @param path
 * @param getLockTimeout 获取锁超时时间(单位ms)
 * @param task
 * @auth anduo 2015年5月8日
 */
public void distributeLock(String path, int getLockTimeout, Runnable task) {
    InterProcessMutex lock = new InterProcessMutex(client, path);
    try {
        LOGGER.debug("尝试获取锁。。。");
        if (lock.acquire(getLockTimeout, TimeUnit.MILLISECONDS)) {
            try {
                LOGGER.debug("获得锁,开始执行任务。。。");
                task.run();
            } finally {
                lock.release();
                LOGGER.debug("释放锁,path:" + path);
            }
        } else {
            LOGGER.info("任务执行失败,在时间:" + getLockTimeout + "ms内,未获得分布式锁!");
        }
    } catch (Exception e) {
        LOGGER.error("执行分布式锁任务异常。", e);
    }

}
 
Example 9
Source File: ZooKeeperCommandExecutor.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private SafeLock safeLock(String executionPath) {
    final InterProcessMutex mtx = mutexMap.computeIfAbsent(
            executionPath, k -> new InterProcessMutex(curator, absolutePath(LOCK_PATH, executionPath)));

    try {
        mtx.acquire();
    } catch (Exception e) {
        logger.error("Failed to acquire a lock for {}; entering read-only mode", executionPath, e);
        stopLater();
        throw new ReplicationException("failed to acquire a lock for " + executionPath, e);
    }

    return () -> {
        try {
            mtx.release();
        } catch (Exception ignored) {
            // Ignore.
        }
    };
}
 
Example 10
Source File: ZooLockAspect.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 环绕操作
 *
 * @param point 切入点
 * @return 原方法返回值
 * @throws Throwable 异常信息
 */
@Around("doLock()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    Object[] args = point.getArgs();
    ZooLock zooLock = method.getAnnotation(ZooLock.class);
    if (StrUtil.isBlank(zooLock.key())) {
        throw new RuntimeException("分布式锁键不能为空");
    }
    String lockKey = buildLockKey(zooLock, method, args);
    InterProcessMutex lock = new InterProcessMutex(zkClient, lockKey);
    try {
        // 假设上锁成功,以后拿到的都是 false
        if (lock.acquire(zooLock.timeout(), zooLock.timeUnit())) {
            return point.proceed();
        } else {
            throw new RuntimeException("请勿重复提交");
        }
    } finally {
        lock.release();
    }
}
 
Example 11
Source File: SpringBootDemoZookeeperApplicationTests.java    From spring-boot-demo with MIT License 6 votes vote down vote up
public void manualBuy() {
    String lockPath = "/buy";
    log.info("try to buy sth.");
    try {
        InterProcessMutex lock = new InterProcessMutex(zkClient, lockPath);
        try {
            if (lock.acquire(1, TimeUnit.MINUTES)) {
                doBuy();
                log.info("buy successfully!");
            }
        } finally {
            lock.release();
        }
    } catch (Exception e) {
        log.error("zk error");
    }
}
 
Example 12
Source File: SetupSteps.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private void releaseLock(InterProcessMutex lock) {
    try {
        lock.release();
        LOG.info("Released lock after running setup.");
    } catch (Exception e) {
        LOG.error("Error releasing acquired lock.", e);
    }
}
 
Example 13
Source File: ZookeeperLock.java    From conductor with Apache License 2.0 5 votes vote down vote up
public void releaseLock(String lockId) {
    if (StringUtils.isEmpty(lockId)) {
        throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId);
    }
    try {
        InterProcessMutex lock = zkLocks.getIfPresent(lockId);
        if (lock != null) {
            lock.release();
        }
    } catch (Exception e) {
        LOGGER.debug("Failed in releaseLock: ", e);
    }
}
 
Example 14
Source File: ZktoXmlMain.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private static void initZKIfNot(CuratorFramework zkConn) throws Exception {
    String confInited = KVPathUtil.getConfInitedPath();
    //init conf if not
    if (zkConn.checkExists().forPath(confInited) == null) {
        InterProcessMutex confLock = new InterProcessMutex(zkConn, KVPathUtil.getConfInitLockPath());
        //someone acquired the lock
        if (!confLock.acquire(100, TimeUnit.MILLISECONDS)) {
            //loop wait for initialized
            while (true) {
                if (!confLock.acquire(100, TimeUnit.MILLISECONDS)) {
                    LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1000));
                } else {
                    try {
                        if (zkConn.checkExists().forPath(confInited) == null) {
                            XmltoZkMain.initFileToZK();
                        }
                        break;
                    } finally {
                        confLock.release();
                    }
                }
            }
        } else {
            try {
                XmltoZkMain.initFileToZK();
            } finally {
                confLock.release();
            }
        }
    }
}
 
Example 15
Source File: CuratorFacade.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
/**
 * 释放对应路径的锁
 *
 * @param path 路径
 */
public void unlock(String path) throws Exception {
    InterProcessMutex lock = lockMap.get(path);
    if (null == lock) {
        throw new IllegalStateException("path " + path + " lock state is wrong.");
    }
    lock.release();
}
 
Example 16
Source File: ZkLockUtil.java    From spring-boot-seckill with GNU General Public License v2.0 5 votes vote down vote up
public static void release(String lockKey){
  	try {
  		InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock/"+lockKey); 
  		mutex.release();
} catch (Exception e) {
	e.printStackTrace();
}
  }
 
Example 17
Source File: EtlLock.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
public void unlock(String key) {
    if (mode == Mode.LOCAL) {
        getLock(key).unlock();
    } else {
        InterProcessMutex lock = getRemoteLock(key);
        try {
            lock.release();
        } catch (Exception e) {
            // ignore
        }
    }
}
 
Example 18
Source File: CuratorMutex.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void release(InterProcessMutex mutex) {
    try {
        mutex.release();
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 19
Source File: DataHostDisable.java    From dble with GNU General Public License v2.0 4 votes vote down vote up
public static boolean disableWithZK(int id, PhysicalDataHost dh, String subHostName, ManagerConnection mc) {
    CuratorFramework zkConn = ZKUtils.getConnection();
    InterProcessMutex distributeLock = new InterProcessMutex(zkConn, KVPathUtil.getHaLockPath(dh.getHostName()));
    try {
        boolean locked = false;
        try {
            if (!distributeLock.acquire(100, TimeUnit.MILLISECONDS)) {
                mc.writeErrMessage(ErrorCode.ER_YES, "Other instance is change the dataHost status");
                HaConfigManager.getInstance().haFinish(id, "Other instance is changing the dataHost, please try again later.", null);
                return false;
            }
            locked = true;
            //local set disable
            final String result = dh.disableHosts(subHostName, false);
            // update total dataHost status
            setStatusToZK(KVPathUtil.getHaStatusPath(dh.getHostName()), zkConn, dh.getClusterHaJson());
            // write out notify message ,let other dble to response
            setStatusToZK(KVPathUtil.getHaResponsePath(dh.getHostName()), zkConn, new HaInfo(dh.getHostName(),
                    ClusterGeneralConfig.getInstance().getValue(ClusterParamCfg.CLUSTER_CFG_MYID),
                    HaInfo.HaType.DATAHOST_DISABLE,
                    HaInfo.HaStatus.SUCCESS
            ).toString());
            //write out self change success result
            ZKUtils.createTempNode(KVPathUtil.getHaResponsePath(dh.getHostName()), ZkConfig.getInstance().getValue(ClusterParamCfg.CLUSTER_CFG_MYID),
                    ClusterPathUtil.SUCCESS.getBytes(StandardCharsets.UTF_8));
            //change stage into waiting others
            HaConfigManager.getInstance().haWaitingOthers(id);
            //use zk to waiting other dble to response
            String errorMessage = isZKfinished(zkConn, KVPathUtil.getHaResponsePath(dh.getHostName()));

            //change stage into finished
            HaConfigManager.getInstance().haFinish(id, errorMessage, result);
            if (errorMessage != null && !"".equals(errorMessage)) {
                mc.writeErrMessage(ErrorCode.ER_YES, errorMessage);
                return false;
            }
        } finally {
            if (locked) {
                distributeLock.release();
            }
            LOGGER.info("reload config: release distributeLock " + KVPathUtil.getConfChangeLockPath() + " from zk");
        }
    } catch (Exception e) {
        LOGGER.info("reload config using ZK failure", e);
        mc.writeErrMessage(ErrorCode.ER_YES, e.getMessage());
        HaConfigManager.getInstance().haFinish(id, e.getMessage(), null);
        return false;
    }
    return true;
}
 
Example 20
Source File: MetadataHelperUpdateHdfsListener.java    From datawave with Apache License 2.0 4 votes vote down vote up
private void maybeUpdateTypeMetadataInHdfs(final SharedCacheCoordinator watcher, String triStateName, String metadataTableName) throws Exception {
    
    boolean locked = false;
    InterProcessMutex lock = (InterProcessMutex) watcher.getMutex("lock");
    try {
        locked = lock.acquire(this.lockWaitTime, TimeUnit.MILLISECONDS);
        if (!locked)
            log.debug("table:" + metadataTableName + " Unable to acquire lock to update " + metadataTableName
                            + ". Another webserver is updating the typeMetadata.");
        else
            log.debug("table:" + metadataTableName + " Obtained lock on updateTypeMetadata for " + metadataTableName);
    } catch (Exception e) {
        log.warn("table:" + metadataTableName + " Got Exception trying to acquire lock to update " + metadataTableName + ".", e);
    }
    
    try {
        if (locked) {
            try {
                log.debug("table:" + metadataTableName + " checkTriState(" + triStateName + ", " + SharedTriState.STATE.NEEDS_UPDATE);
                if (watcher.checkTriState(triStateName, SharedTriState.STATE.NEEDS_UPDATE)) {
                    if (log.isDebugEnabled()) {
                        log.debug("table:" + metadataTableName + " " + this + " STATE is NEEDS_UPDATE. Will write the TypeMetadata map to hdfs");
                    }
                    watcher.setTriState(triStateName, SharedTriState.STATE.UPDATING);
                    if (log.isDebugEnabled()) {
                        log.debug("table:" + metadataTableName + " " + this + " setTriState to UPDATING");
                    }
                    // get a connection for my MetadataHelper, and get the TypeMetadata map
                    ZooKeeperInstance instance = new ZooKeeperInstance(ClientConfiguration.loadDefault().withInstance(this.instance)
                                    .withZkHosts(this.zookeepers));
                    Connector connector = instance.getConnector(this.username, new PasswordToken(this.password));
                    TypeMetadataHelper typeMetadataHelper = this.typeMetadataHelperFactory.createTypeMetadataHelper(connector, metadataTableName,
                                    allMetadataAuths, false);
                    typeMetadataWriter.writeTypeMetadataMap(typeMetadataHelper.getTypeMetadataMap(this.allMetadataAuths), metadataTableName);
                    if (log.isDebugEnabled()) {
                        log.debug("table:" + metadataTableName + " " + this + " set the sharedTriState needsUpdate to UPDATED for " + metadataTableName);
                    }
                    watcher.setTriState(triStateName, SharedTriState.STATE.UPDATED);
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("table:"
                                        + metadataTableName
                                        + " "
                                        + this
                                        + "  STATE is not NEEDS_UPDATE! Someone else may be writing or has already written the TypeMetadata map, just release the lock");
                    }
                }
            } catch (Exception ex) {
                log.warn("table:" + metadataTableName + " Unable to write TypeMetadataMap for " + metadataTableName, ex);
                watcher.setTriState(triStateName, SharedTriState.STATE.NEEDS_UPDATE);
                if (log.isDebugEnabled()) {
                    log.debug("After exception, set the SharedTriState STATE to NEEDS_UPDATE");
                }
                
            }
        }
    } finally {
        if (locked) {
            lock.release();
            if (log.isTraceEnabled())
                log.trace("table:" + metadataTableName + " " + this + " released the lock for " + metadataTableName);
            
        }
    }
}