当前位置: 首页>>代码示例>>Java>>正文


Java InterProcessMutex.acquire方法代码示例

本文整理汇总了Java中org.apache.curator.framework.recipes.locks.InterProcessMutex.acquire方法的典型用法代码示例。如果您正苦于以下问题:Java InterProcessMutex.acquire方法的具体用法?Java InterProcessMutex.acquire怎么用?Java InterProcessMutex.acquire使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.curator.framework.recipes.locks.InterProcessMutex的用法示例。


在下文中一共展示了InterProcessMutex.acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: tryLock

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
@Override
public boolean tryLock(String key) {
    try {
        InterProcessMutex mutex = locks.computeIfAbsent(key,
                __ -> new InterProcessMutex(curatorFramework, String.join("/", basePath, key)));
        
        
        boolean owned = mutex.isAcquiredInThisProcess();
        if(owned) {
            return true;
        } else {
            mutex.acquire(timeout, TimeUnit.MILLISECONDS);
        }
        return mutex.isAcquiredInThisProcess();
    } catch (Exception e) {
        return false;
    }
}
 
开发者ID:benson-git,项目名称:ibole-microservice,代码行数:19,代码来源:DistributedLockServiceCuratorImpl.java

示例2: inMutex

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
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.getMillis(), TimeUnit.MILLISECONDS)) {
            try {
                work.run();
            } finally {
                mutex.release();
            }
        } else {
            _log.warn("could not acquire index lock after {} millis!!", LOCK_ACQUIRE_TIMEOUT.getMillis());
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:18,代码来源:CreateKeyspacesCommand.java

示例3: tryLock

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
@Override
public boolean tryLock(String key) {
    try {
        InterProcessMutex mutex = locks.computeIfAbsent(key,
                __ -> new InterProcessMutex(curatorFramework, String.join("/", basePath, key)));


        boolean owned = mutex.isAcquiredInThisProcess();
        if(owned) {
            return true;
        } else {
            mutex.acquire(timeout, TimeUnit.MILLISECONDS);
        }
        return mutex.isAcquiredInThisProcess();
    } catch (Exception e) {
        return false;
    }
}
 
开发者ID:aol,项目名称:micro-server,代码行数:19,代码来源:DistributedLockServiceCuratorImpl.java

示例4: runSetup

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
/**
 * Call each registered {@link SetupStep} one after the other.
 * @throws SetupException Thrown with any error during running setup, including Zookeeper interactions, and
 *                          individual failures in the {@link SetupStep}.
 */
@PostConstruct
public void runSetup() throws SetupException {
    HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration);
    InterProcessMutex lock = curatorFactory.lockInstance(zookeeperProperties.getZkRoot());
    try {
        LOG.info("Trying to acquire lock for running setup.");
        lock.acquire();
        LOG.info("Acquired lock for running setup.");
        handleSetupInProgress(configuration, zookeeperProperties);
        for (SetupStep step : setupSteps) {
            LOG.info("Running setup step: {}", step);
            step.run();
        }
        clearSetupInProgress(zookeeperProperties);
    } catch (SetupException se) {
        LOG.error("Got setup exception while trying to setup", se);
        throw se;
    } catch (Throwable e) {
        LOG.error("Error running setup steps", e);
        throw new SetupException("Error running setup steps", e);
    } finally {
        releaseLock(lock);
        curatorFactory.close();
    }
}
 
开发者ID:apache,项目名称:incubator-atlas,代码行数:31,代码来源:SetupSteps.java

示例5: distributeLock

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
/**
 * 使用分布式锁执行任务
 *
 * @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);
    }

}
 
开发者ID:classtag,项目名称:scratch_zookeeper_netty,代码行数:29,代码来源:ZKClientImpl.java

示例6: safeLock

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
private SafeLock safeLock(String executionPath) {
    InterProcessMutex mtx = mutexMap.computeIfAbsent(
            executionPath, k -> new InterProcessMutex(curator, absolutePath(LOCK_PATH, executionPath)));

    try {
        mtx.acquire();
    } catch (Exception e) {
        throw new ReplicationException(e);
    }

    return mtx::release;
}
 
开发者ID:line,项目名称:centraldogma,代码行数:13,代码来源:ZooKeeperCommandExecutor.java

示例7: initZKIfNot

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
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();
            }
        }
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:32,代码来源:ZktoXmlMain.java

示例8: acquire

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
private InterProcessMutex acquire(Duration acquireTimeout) {
    InterProcessMutex mutex = new InterProcessMutex(_curatorFramework, _path);
    try {
        if (!mutex.acquire(acquireTimeout.getMillis(), TimeUnit.MILLISECONDS)) {
            throw new TimeoutException();
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    return mutex;
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:12,代码来源:CuratorMutex.java

示例9: call

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
@Override
public AtomicLong call() throws Exception {

	while (true) {
		InterProcessMutex lock = new InterProcessMutex(client, "/lock/" + name);
		try {
			if (null != client.checkExists().forPath("/seq/" + name)) {// 已经存在
				lock.acquire();
				return getCurrentMaxIndex();
			} else {// 不存在
				lock.acquire();
				if (null == client.checkExists().forPath("/seq/" + name)) {
					String data = String.valueOf(incrStep);
					client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
							.forPath("/seq/" + name, data.getBytes(Charset.forName("UTF-8")));
					boundaryMaxValue = incrStep;
					return new AtomicLong(0);
				} else {
					return getCurrentMaxIndex();
				}
			}
		} catch(Exception e){
			
			if(retry-- == 0){
				throw e;
			}
		}finally {
			lock.release();
		}

	}

}
 
开发者ID:balancebeam,项目名称:sherlock,代码行数:34,代码来源:ZKPartitionSequenceGenerator.java

示例10: acquire

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
private static boolean acquire(InterProcessMutex lock) {
	try {
		return lock.acquire(2, TimeUnit.SECONDS);
	} catch (Exception e) {
		throw new RuntimeException("Exception acquiring Zookeeper lock", e);
	}
}
 
开发者ID:bootique,项目名称:bootique-job,代码行数:8,代码来源:ZkMutex.java

示例11: doStart

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
protected void doStart() throws Exception {

        int i = startingId;

        while (this.id == -1) {

            String lockPath = ZKPaths.makePath(locksBasePath, String.valueOf(i));
            String memberPath = ZKPaths.makePath(membersBasePath, String.valueOf(i));

            log.trace("Acquiring mutex for member {} via lock path {}", i, lockPath);

            InterProcessMutex mutex = new InterProcessMutex(this.client, lockPath);
            mutex.acquire();

            log.debug("Acquired mutex for member {} via lock path {}", i, lockPath);

            try {

                Stat stat = client.checkExists().creatingParentContainersIfNeeded().forPath(memberPath);

                if (stat == null) {

                    log.debug("Claiming container id {} via member path {}", i, memberPath);

                    try {
                        //no peer has this node yet, grab it:
                        pen = new PersistentNode(client, CreateMode.EPHEMERAL, false, memberPath, payload);
                        pen.start();
                        pen.waitForInitialCreate(30000, TimeUnit.SECONDS);
                        this.id = i;
                        log.info("Claimed container id {} via member path {}", i, memberPath);
                        return;
                    } catch (InterruptedException e) {
                        CloseableUtils.closeQuietly(pen);
                        ThreadUtils.checkInterrupted(e);
                        Throwables.propagate(e);
                    }
                }

            } finally {
                mutex.release();
                log.debug("Released mutex for member {} via lock path {}", i, lockPath);
            }

            i++;
        }
    }
 
开发者ID:stormpath,项目名称:samza-spring-boot-starter,代码行数:48,代码来源:SequentialGroupMember.java

示例12: adoptRemotePartition

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
public void adoptRemotePartition(Partition partitionToTakeIn) throws Exception {
    String adZNode = ADOPTION_ADS_ROOT_ZNODE + "/" + partitionToTakeIn.getPartitionFullNameWithBrokerId();
    logger.debug("Will try to adopt Partition {}", adZNode);
    //try to lock the Ad first and then initiate the adoption process
    String adZNodeLockPath = ADOPTION_ADS_LOCK_ROOT_ZNODE + "/" + partitionToTakeIn.getPartitionFullNameWithBrokerId();
    InterProcessMutex lock = new InterProcessMutex(client, adZNodeLockPath);
    if ( lock.acquire(30000, TimeUnit.MILLISECONDS) )
    {
        logger.debug("Successfully acquired lock on Ad: {}", adZNodeLockPath);
        try
        {
            //check again if the Ad is still valid
            if(new String(client.getData().forPath(adZNode)).equals(AD_POSTING_TEXT)) {
                boolean reassignmentSucceeded = reassignPartitionToLocalBroker(
                        partitionToTakeIn.brokerId,
                        partitionToTakeIn.topicName,
                        partitionToTakeIn.partitionId,
                        Utils.getLocalBrokerId(),
                        adZNode);
                logger.debug("Reassignment succeeded: {}", reassignmentSucceeded);
            }
            else {
                logger.debug("Ad {} seems stale. Skipping adoption process", adZNode);
            }
        }
        finally
        {
            lock.release();
            while(true) {
                try {
                    client.delete().forPath(adZNodeLockPath);
                    break;
                }
                catch(KeeperException.NoNodeException noNodeEx) {
                    //ignore and break
                    break;
                }
                catch (Exception ex) {
                    logger.debug("Trying to delete {} after releasing lock but got exception {}. Will retry", adZNodeLockPath, ex);
                }
            }
        }
    }
    else {
        logger.debug("Failed to acquire lock on Ad: {}", adZNodeLockPath);
    }
}
 
开发者ID:Microsoft,项目名称:Cluster-Partition-Rebalancer-For-Kafka,代码行数:48,代码来源:ZookeeperBackedAdoptionLogicImpl.java

示例13: reassignPartitionToLocalBroker

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
private boolean reassignPartitionToLocalBroker(int remoteBrokerId, String topicName, int partitionId, int localBrokerId, String adZNode) throws Exception {
    boolean succeeded = false;
    String reassignmentConfigFileName = "partitions-to-move.json." + System.currentTimeMillis();
    String reassignmentProcessLockPath = ADOPTION_ADS_LOCK_ROOT_ZNODE;
    InterProcessMutex lock = new InterProcessMutex(client, reassignmentProcessLockPath);
    while(!succeeded) {
        if (lock.acquire(30000, TimeUnit.MILLISECONDS) )
        {
            logger.debug("Locking {} succeeded", reassignmentProcessLockPath);
            try {
                String currentReplicas = Utils.getReplicasOfTopicPartition(client, topicName, partitionId);
                String desiredReplicas = currentReplicas.replace(""+remoteBrokerId, ""+localBrokerId);
                String reassignmentJson = String.format("{\"partitions\":[{\"topic\":\"%s\",\"partition\":%d,\"replicas\":[%s]}],\"version\":1}", topicName, partitionId, desiredReplicas);
                //do kafka reassignment
                PrintWriter out = new PrintWriter(reassignmentConfigFileName);
                out.println( reassignmentJson );
                out.close();
                logger.debug("Reassignment will be kicked for {}", reassignmentJson);
                String[] reassignCmdArgs = {
                        "--reassignment-json-file=" + reassignmentConfigFileName,
                        "--zookeeper=" + client.getZookeeperClient().getCurrentConnectionString(),
                        "--execute"
                };
                ReassignPartitionsCommand.main(reassignCmdArgs);
                //Hacky: Restart kafka controller. Controller seems buggy sometimes
                Utils.restartKafkaController(client);
                //Hacky: Sleep for 5 mins to let the reassignment process complete
                logger.debug("Reassignment command has been initiated. Will sleep for {} ms", 10 * 60000);
                Thread.sleep(10 * 60000);

                Files.deleteIfExists(Paths.get(reassignmentConfigFileName));

                logger.debug("Setting data for Ad {} as {}", adZNode, AD_ADOPTION_COMPLETE_TEXT + "-" + localBrokerId);
                //mark the ad as done
                client.setData().forPath(adZNode, (AD_ADOPTION_COMPLETE_TEXT + "-" + localBrokerId).getBytes());
                succeeded = true;
            } finally {
                lock.release();
            }
        } else {
            logger.debug("Locking {} failed. Will probably retry", reassignmentProcessLockPath);
            //check if ad is still valid, otherwise break retry loop
            if(!new String(client.getData().forPath(adZNode)).equals(AD_POSTING_TEXT)) {
                logger.debug("Ad {} has expired. Quit trying to reassign", adZNode);
                break;
            }
            else {
                logger.debug("Ad {} is still valid. Will retry", adZNode);
            }
        }
    }

    return succeeded;
}
 
开发者ID:Microsoft,项目名称:Cluster-Partition-Rebalancer-For-Kafka,代码行数:55,代码来源:ZookeeperBackedAdoptionLogicImpl.java

示例14: acquireMutex

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
private boolean acquireMutex(InterProcessMutex mutex)
        throws Exception {
    return mutex.acquire(200, TimeUnit.MILLISECONDS);
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:5,代码来源:DefaultJobService.java

示例15: checkCollectionExists

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入方法依赖的package包/类
protected void checkCollectionExists(CloudSolrClient cloudSolrClient, String collection) throws Exception {
  if (!cloudSolrClient.getZkStateReader().getClusterState().hasCollection(collection)) {

    synchronized (this) {
      if (curatorClient == null) {
        curatorClient = CuratorFrameworkFactory.newClient(cloudSolrClient.getZkHost(), new ExponentialBackoffRetry(1000, 3));
        curatorClient.start();
      }
    }

    String lockPath = lockZnodePath+"/"+collection;
    InterProcessMutex lock = new InterProcessMutex(curatorClient, lockPath);
    try {
      if (!lock.acquire(60, TimeUnit.SECONDS)) {
        // couldn't acquire the lock, but let's check to see if the collection was created before failing
        cloudSolrClient.getZkStateReader().updateClusterState();
        if (!cloudSolrClient.getZkStateReader().getClusterState().hasCollection(collection)) {
          throw new IllegalStateException("Failed to acquire the create collection lock within 60 seconds! Cannot create "+collection);
        }
      }

      // we have the lock here ...
      cloudSolrClient.getZkStateReader().updateClusterState();
      if (!cloudSolrClient.getZkStateReader().getClusterState().hasCollection(collection)) {
        log.info("Acquired inter-process lock for creating " + collection);

        // ok, it doesn't exist ... go ahead and create it
        long startMs = System.currentTimeMillis();
        createCollection(cloudSolrClient, collection);
        log.info("Collection created, took "+(System.currentTimeMillis()-startMs)+" ms ... updating alias: "+alias);

        // add the new collection to the collection alias if one is registered
        if (alias != null) {
          List<String> aliasList = getAliasList(cloudSolrClient, alias);
          if (!aliasList.contains(collection)) {
            aliasList.add(collection);
            log.info("Added " + collection + " to the " + alias + " alias");

            // trim the alias down to the desired size
            int numColls = aliasList.size();
            if (maxCollectionsInAlias > 0 && numColls > maxCollectionsInAlias) {
              Collections.sort(aliasList);

              int numToRemove = numColls - maxCollectionsInAlias;
              aliasList = aliasList.subList(numToRemove, numColls);
              log.info("Removed "+numToRemove+" collections from alias: "+aliasList);
            }

            CollectionAdminRequest.CreateAlias createAliasCmd = new CollectionAdminRequest.CreateAlias();
            createAliasCmd.setAliasName(alias);
            createAliasCmd.setAliasedCollections(StrUtils.join(aliasList, ','));
            cloudSolrClient.request(createAliasCmd);
          }
        }
      } else {
        log.info("Collection "+collection+" was created by another process while we were waiting to acquire the lock ...");
      }
    } finally {
      lock.release();
    }
  }
}
 
开发者ID:lucidworks,项目名称:storm-solr,代码行数:63,代码来源:CollectionPerTimeFrameAssignmentStrategy.java


注:本文中的org.apache.curator.framework.recipes.locks.InterProcessMutex.acquire方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。