org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex Java Examples

The following examples show how to use org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex. 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: MultiSharedLockTest.java    From BigData-In-Practice with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CuratorFramework client = ZKUtils.getClient();
    client.start();

    InterProcessLock lock1 = new InterProcessMutex(client, lockPath1); // 可重入锁
    InterProcessLock lock2 = new InterProcessSemaphoreMutex(client, lockPath2); // 不可重入锁
    // 组锁,多锁
    InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(lock1, lock2));
    if (!lock.acquire(10, TimeUnit.SECONDS)) {
        throw new IllegalStateException("不能获取多锁");
    }
    System.out.println("已获取多锁");
    System.out.println("是否有第一个锁: " + lock1.isAcquiredInThisProcess());
    System.out.println("是否有第二个锁: " + lock2.isAcquiredInThisProcess());
    try {
        resource.use(); // 资源操作
    } finally {
        System.out.println("释放多个锁");
        lock.release(); // 释放多锁
    }
    System.out.println("是否有第一个锁: " + lock1.isAcquiredInThisProcess());
    System.out.println("是否有第二个锁: " + lock2.isAcquiredInThisProcess());
    client.close();
    System.out.println("结束!");
}
 
Example #2
Source File: CuratorLocker.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an exclusive lock on service-specific ZK node to ensure two schedulers aren't running
 * simultaneously for the same service.
 */
// SUPPRESS CHECKSTYLE ReturnCount
@VisibleForTesting
void lockInternal() {
  if (curatorClient != null) {
    throw new IllegalStateException("Already locked");
  }
  curatorClient = clientBuilder.build();
  curatorClient.start();

  final String lockPath = PersisterUtils.joinPaths(
      CuratorUtils.getServiceRootPath(serviceName),
      LOCK_PATH_NAME);

  LOGGER.info("Acquiring ZK lock on {}...", lockPath);
  final String failureLogMsg = String.format("Failed to acquire ZK lock on %s. " +
          "Duplicate service named '%s', or recently restarted instance of '%s'?",
      lockPath, serviceName, serviceName);
  try {
    InterProcessSemaphoreMutex curatorMutexInternal = new InterProcessSemaphoreMutex(
        curatorClient,
        lockPath);
    // Start at 1 for pretty display of "1/3" through "3/3":
    for (int attempt = 1; attempt < LOCK_ATTEMPTS + 1; ++attempt) {
      if (curatorMutexInternal.acquire(10, getWaitTimeUnit())) {
        LOGGER.info("{}/{} Lock acquired.", attempt, LOCK_ATTEMPTS);
        this.curatorMutex = curatorMutexInternal;
        return;
      }
      if (attempt < LOCK_ATTEMPTS) {
        LOGGER.error("{}/{} {} Retrying lock...", attempt, LOCK_ATTEMPTS, failureLogMsg);
      }
    }
    LOGGER.error(failureLogMsg + " Restarting scheduler process to try again.");
  } catch (Exception ex) { // SUPPRESS CHECKSTYLE IllegalCatch
    LOGGER.error(String.format("Error acquiring ZK lock on path: %s", lockPath), ex);
  }
  curatorClient = null;
  exit();
}
 
Example #3
Source File: ZookeeperBasedJobLock.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public ZookeeperBasedJobLock(Properties properties, String jobName)  {
  this.lockAcquireTimeoutMilliseconds =
      getLong(properties, LOCKS_ACQUIRE_TIMEOUT_MILLISECONDS, LOCKS_ACQUIRE_TIMEOUT_MILLISECONDS_DEFAULT);
  this.lockPath = Paths.get(LOCKS_ROOT_PATH, jobName).toString();
  initializeCuratorFramework(properties);
  lock = new InterProcessSemaphoreMutex(curatorFramework, lockPath);
}
 
Example #4
Source File: InterProcessMultiLockExample.java    From ZKRecipesByExample with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	FakeLimitedResource resource = new FakeLimitedResource();
	try (TestingServer server = new TestingServer()) {
		CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
		client.start();
		
		InterProcessLock lock1 = new InterProcessMutex(client, PATH1);
		InterProcessLock lock2 = new InterProcessSemaphoreMutex(client, PATH2);
		
		InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(lock1, lock2));

		if (!lock.acquire(10, TimeUnit.SECONDS)) {
			throw new IllegalStateException("could not acquire the lock");
		}
		System.out.println("has the lock");
		
		System.out.println("has the lock1: " + lock1.isAcquiredInThisProcess());
		System.out.println("has the lock2: " + lock2.isAcquiredInThisProcess());
		
		try {			
			resource.use(); //access resource exclusively
		} finally {
			System.out.println("releasing the lock");
			lock.release(); // always release the lock in a finally block
		}
		System.out.println("has the lock1: " + lock1.isAcquiredInThisProcess());
		System.out.println("has the lock2: " + lock2.isAcquiredInThisProcess());
	}
}
 
Example #5
Source File: RecipesManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception {
    try (CuratorFramework client = newClient()) {
        client.start();
        InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A");

        sharedLock.acquire();

        // Do process A

        sharedLock.release();
    }
}
 
Example #6
Source File: SharedLockTest.java    From BigData-In-Practice with Apache License 2.0 4 votes vote down vote up
/**
     * 请求锁,使用资源,释放锁
     */
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < clientNums; i++) {
            String clientName = "client#" + i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    CuratorFramework client = ZKUtils.getClient();
                    client.start();
                    Random random = new Random();
                    try {
                        final InterProcessSemaphoreMutex lock = new InterProcessSemaphoreMutex(client, lockPath);
                        // 每个客户端请求10次共享资源
                        for (int j = 0; j < 10; j++) {
                            if (!lock.acquire(10, TimeUnit.SECONDS)) {
                                throw new IllegalStateException(j + ". " + clientName + " 不能得到互斥锁");
                            }
                            try {
                                System.out.println(j + ". " + clientName + " 已获取到互斥锁");
                                resource.use(); // 使用资源
//                                if (!lock.acquire(10, TimeUnit.SECONDS)) {
//                                    throw new IllegalStateException(j + ". " + clientName + " 不能再次得到互斥锁");
//                                }
//                                System.out.println(j + ". " + clientName + " 已再次获取到互斥锁");
//                                lock.release(); // 申请几次锁就要释放几次锁
                            } finally {
                                System.out.println(j + ". " + clientName + " 释放互斥锁");
                                lock.release(); // 总是在finally中释放
                            }
                            Thread.sleep(random.nextInt(100));
                        }
                    } catch (Throwable e) {
                        System.out.println(e.getMessage());
                    } finally {
                        CloseableUtils.closeQuietly(client);
                        System.out.println(clientName + " 客户端关闭!");
                        countDownLatch.countDown();
                    }
                }
            }).start();
        }
        countDownLatch.await();
        System.out.println("结束!");
    }
 
Example #7
Source File: CuratorStateManager.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
private DistributedLock(CuratorFramework client, String path) {
  this.path = path;
  this.lock = new InterProcessSemaphoreMutex(client, path);
}
 
Example #8
Source File: SharedNonReentrantLock.java    From micro-service with MIT License 4 votes vote down vote up
public SharedNonReentrantLock(CuratorFramework client, String clientName) {
    lock = new InterProcessSemaphoreMutex(client, lockPath);
    this.clientName = clientName;
}
 
Example #9
Source File: ExampleClientSharedLocks.java    From ZKRecipesByExample with Apache License 2.0 4 votes vote down vote up
public ExampleClientSharedLocks(CuratorFramework client, String lockPath, FakeLimitedResource resource, String clientName) {
	this.resource = resource;
	this.clientName = clientName;
	lock = new InterProcessSemaphoreMutex(client, lockPath);
}
 
Example #10
Source File: MigrationManager.java    From curator with Apache License 2.0 3 votes vote down vote up
/**
 * Process the given migration set
 *
 * @param set the set
 * @return completion stage. If there is a migration-specific error, the stage will be completed
 * exceptionally with {@link org.apache.curator.x.async.migrations.MigrationException}.
 */
public CompletionStage<Void> migrate(MigrationSet set)
{
    InterProcessLock lock = new InterProcessSemaphoreMutex(client.unwrap(), ZKPaths.makePath(lockPath, set.id()));
    CompletionStage<Void> lockStage = lockAsync(lock, lockMax.toMillis(), TimeUnit.MILLISECONDS, executor);
    return lockStage.thenCompose(__ -> runMigrationInLock(lock, set));
}