org.apache.curator.framework.recipes.atomic.DistributedAtomicLong Java Examples

The following examples show how to use org.apache.curator.framework.recipes.atomic.DistributedAtomicLong. 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: ZookeeperQueryLock.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public void startQuery() throws Exception {
    // increment the zookeeper query file
    clientLock.lock();
    try {
        DistributedAtomicLong atomicLong = getLong();
        AtomicValue<Long> longValue = atomicLong.increment();
        if (!longValue.succeeded()) {
            throw new ZookeeperLockException("Unable to start query");
        }
        if (log.isTraceEnabled()) {
            long preValue = longValue.preValue();
            long postValue = longValue.postValue();
            log.trace("Updated value for " + getQueryFile() + " from " + preValue + " to " + postValue);
        }
    } finally {
        clientLock.unlock();
    }
}
 
Example #2
Source File: ZookeeperQueryLock.java    From datawave with Apache License 2.0 6 votes vote down vote up
public void stopQuery() throws Exception {
    // decrement the zookeeper query file and delete if 0
    clientLock.lock();
    try {
        DistributedAtomicLong atomicLong = getLong();
        AtomicValue<Long> longValue = atomicLong.decrement();
        if (!longValue.succeeded()) {
            throw new ZookeeperLockException("Unable to stop query");
        }
        long postValue = longValue.postValue();
        if (log.isTraceEnabled()) {
            long preValue = longValue.preValue();
            log.trace("Updated value for " + getQueryFile() + " from " + preValue + " to " + postValue);
        }
        if (postValue == 0) {
            client.delete().forPath(getQueryFile());
        }
    } finally {
        clientLock.unlock();
    }
}
 
Example #3
Source File: ZookeeperQueryLock.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isQueryRunning() {
    // check existence of the query file
    clientLock.lock();
    try {
        DistributedAtomicLong atomicLong = getLong();
        AtomicValue<Long> longValue = atomicLong.get();
        if (!longValue.succeeded()) {
            throw new ZookeeperLockException("Unable to get query lock count");
        }
        long postValue = longValue.postValue();
        if (log.isTraceEnabled()) {
            log.trace("Got value for " + getQueryFile() + " to be " + postValue);
        }
        return postValue > 0;
    } catch (Exception e) {
        log.error("Unable to determine if zookeeper lock exists", e);
        // assume the query is still running for now
        return true;
    } finally {
        clientLock.unlock();
    }
}
 
Example #4
Source File: ZkService.java    From DBus with Apache License 2.0 5 votes vote down vote up
/**
 * 获得ZK中的当前值,如果不存在,抛出异常
 *
 * @param path
 * @return
 * @throws Exception
 */
private long currentValueFromZk(String path) throws Exception {
    if (isExists(path)) {
        DistributedAtomicLong count = new DistributedAtomicLong(client, path, new RetryNTimes(10, 1000));
        AtomicValue<Long> val = count.get();
        return val.postValue();
    } else {
        throw new RuntimeException("Path is not existed! Call nextValue firstly!");
    }
}
 
Example #5
Source File: ZkService.java    From DBus with Apache License 2.0 5 votes vote down vote up
/**
 * 获得分布式自增变量
 *
 * @param path
 * @return
 * @throws Exception
 */
public Long getIncrementValue(String path) throws Exception {
    DistributedAtomicLong atomicId = new DistributedAtomicLong(client, path, new RetryNTimes(32, 1000));
    AtomicValue<Long> rc = atomicId.get();
    if (rc.succeeded()) {
        logger.debug("getIncrementValue({}) success! get: {}.", path, rc.postValue());
    } else {
        logger.warn("getIncrementValue({}) failed! get: {}.", path, rc.postValue());
    }
    return rc.postValue();
}
 
Example #6
Source File: ZkService.java    From DBus with Apache License 2.0 5 votes vote down vote up
/**
 * 自增并获得,自增后的变量
 *
 * @param path
 * @return
 * @throws Exception
 */
public Long incrementAndGetValue(String path) throws Exception {
    DistributedAtomicLong atomicId = new DistributedAtomicLong(client, path, new RetryNTimes(32, 1000));
    AtomicValue<Long> rc = atomicId.increment();
    if (rc.succeeded()) {
        logger.info("incrementAndGetValue({}) success! before: {}, after: {}.", path, rc.preValue(), rc.postValue());
    } else {
        logger.warn("incrementAndGetValue({}) failed! before: {}, after: {}.", path, rc.preValue(), rc.postValue());
    }
    return rc.postValue();
}
 
Example #7
Source File: ZKTimestampStorage.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@Inject
public ZKTimestampStorage(CuratorFramework zkClient) throws Exception {
    LOG.info("ZK Client state {}", zkClient.getState());
    timestamp = new DistributedAtomicLong(zkClient, TIMESTAMP_ZNODE, new RetryNTimes(3, 1000)); // TODO Configure
    // this?
    if (timestamp.initialize(INITIAL_MAX_TS_VALUE)) {
        LOG.info("Timestamp value in ZNode initialized to {}", INITIAL_MAX_TS_VALUE);
    }
}
 
Example #8
Source File: MockCurator.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public DistributedAtomicLong createAtomicCounter(String path) {
    MockAtomicCounter counter = atomicCounters.get(path);
    if (counter == null) {
        counter = new MockAtomicCounter(path);
        atomicCounters.put(path, counter);
    }
    return counter;
}
 
Example #9
Source File: CuratorCounterTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void testCounter() throws Exception {
    DistributedAtomicLong counter = new MockCurator().createAtomicCounter("/mycounter");
    counter.initialize(4l);
    assertEquals(4l, counter.get().postValue().longValue());
    assertEquals(5l, counter.increment().postValue().longValue());
}
 
Example #10
Source File: DistributedAtomicLongExample.java    From ZKRecipesByExample with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, Exception {
	try (TestingServer server = new TestingServer()) {
		CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
		client.start();

		List<DistributedAtomicLong> examples = Lists.newArrayList();
		ExecutorService service = Executors.newFixedThreadPool(QTY);
		for (int i = 0; i < QTY; ++i) {
			final DistributedAtomicLong count = new DistributedAtomicLong(client, PATH, new RetryNTimes(10, 10));
			
			examples.add(count);
			Callable<Void> task = new Callable<Void>() {
				@Override
				public Void call() throws Exception {
					try {
						//Thread.sleep(rand.nextInt(1000));
						AtomicValue<Long> value = count.increment();
						//AtomicValue<Long> value = count.decrement();
						//AtomicValue<Long> value = count.add((long)rand.nextInt(20));
						System.out.println("succeed: " + value.succeeded());
						if (value.succeeded())
							System.out.println("Increment: from " + value.preValue() + " to " + value.postValue());
					} catch (Exception e) {
						e.printStackTrace();
					}

					return null;
				}
			};
			service.submit(task);
		}

		service.shutdown();
		service.awaitTermination(10, TimeUnit.MINUTES);
	}

}
 
Example #11
Source File: TransactorID.java    From fluo with Apache License 2.0 5 votes vote down vote up
private static Long createID(CuratorFramework curator) {
  try {
    DistributedAtomicLong counter = new DistributedAtomicLong(curator,
        ZookeeperPath.TRANSACTOR_COUNT, new ExponentialBackoffRetry(1000, 10));
    AtomicValue<Long> nextId = counter.increment();
    while (nextId.succeeded() == false) {
      nextId = counter.increment();
    }
    return nextId.postValue();
  } catch (Exception e) {
    throw new IllegalStateException(e);
  }
}
 
Example #12
Source File: ZookeeperQueryLock.java    From datawave with Apache License 2.0 4 votes vote down vote up
private DistributedAtomicLong getLong() {
    getClient();
    return atomicLong;
}
 
Example #13
Source File: MockCurator.java    From vespa with Apache License 2.0 4 votes vote down vote up
/** Returns an atomic counter in this, or empty if no such counter is created */
public Optional<DistributedAtomicLong> counter(String path) {
    return Optional.ofNullable(atomicCounters.get(path));
}
 
Example #14
Source File: Curator.java    From vespa with Apache License 2.0 4 votes vote down vote up
/** For internal use; prefer creating a {@link CuratorCounter} */
public DistributedAtomicLong createAtomicCounter(String path) {
    return new DistributedAtomicLong(curatorFramework, path, new ExponentialBackoffRetry((int) BASE_SLEEP_TIME.toMillis(), MAX_RETRIES));
}