Java Code Examples for org.apache.curator.framework.recipes.shared.SharedCount#close()

The following examples show how to use org.apache.curator.framework.recipes.shared.SharedCount#close() . 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: SharedCacheCoordinator.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Increments the shared distributed counter named {@code counterName} by one.
 */
public void incrementCounter(String counterName) throws Exception {
    ArgumentChecker.notNull(counterName);
    
    SharedCount count = sharedCounters.get(counterName);
    Preconditions.checkArgument(count != null, "Invalid counter name: " + counterName + ". Shared counter may be down.");
    
    VersionedValue<Integer> currentCount = count.getVersionedValue();
    int newCount = currentCount.getValue() + 1;
    int tries = 0;
    while (!count.trySetCount(currentCount, newCount)) {
        currentCount = count.getVersionedValue();
        newCount = currentCount.getValue() + 1;
        if (++tries >= maxRetries) {
            // We've exceeded our max tries to update the counter. Try to re-register it and also throw an exception to
            // indicate that we didn't necessarily update the shared count.
            sharedCounters.remove(counterName);
            count.removeListener(sharedCountListeners.get(counterName));
            count.close();
            reregisterCounter(counterName, sharedCountListeners.get(counterName), newCount);
            throw new IllegalStateException("Unable to increment shared counter " + counterName + " after " + maxRetries
                            + " attempts. Zookeeper connection may be down.");
        }
    }
    localCounters.put(counterName, newCount);
}
 
Example 2
Source File: SharedCacheCoordinator.java    From datawave with Apache License 2.0 5 votes vote down vote up
private void shutdownCounters() {
    for (String counterName : localCounters.keySet()) {
        SharedCount count = sharedCounters.remove(counterName);
        localCounters.put(counterName, count.getCount());
        try {
            count.removeListener(sharedCountListeners.get(counterName));
            count.close();
        } catch (IOException e) {
            // ignore -- we're going to abandon this counter.
            log.warn("Error closing counter " + counterName + " after connection lost.", e);
        }
    }
}
 
Example 3
Source File: TestInterProcessSemaphore.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void testThreadedLeaseIncrease() throws Exception
{
    final Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        client.start();

        final SharedCount count = new SharedCount(client, "/foo/count", 1);
        count.start();

        final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", count);

        ExecutorService service = Executors.newCachedThreadPool();

        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(1);
        Future<Object> future1 = service.submit
            (
                new Callable<Object>()
                {
                    @Override
                    public Object call() throws Exception
                    {
                        Lease lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS);
                        Assert.assertNotNull(lease);
                        latch1.countDown();
                        lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS);
                        Assert.assertNotNull(lease);
                        latch2.countDown();
                        return null;
                    }
                }
            );
        Future<Object> future2 = service.submit
            (
                new Callable<Object>()
                {
                    @Override
                    public Object call() throws Exception
                    {
                        Assert.assertTrue(latch1.await(timing.forWaiting().seconds(), TimeUnit.SECONDS));
                        timing.sleepABit(); // make sure second acquire is waiting
                        Assert.assertTrue(count.trySetCount(2));
                        //Make sure second acquire takes less than full waiting time:
                        timing.sleepABit();
                        Assert.assertTrue(latch2.await(0, TimeUnit.SECONDS));
                        return null;
                    }
                }
            );

        future1.get();
        future2.get();

        count.close();
    }
    finally
    {
        TestCleanState.closeAndTestClean(client);
    }
}
 
Example 4
Source File: SharedCounterExample.java    From ZKRecipesByExample with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException, Exception {
	final Random rand = new Random();
	SharedCounterExample example = new SharedCounterExample();
	try (TestingServer server = new TestingServer()) {
		CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
		client.start();
		
		SharedCount baseCount = new SharedCount(client, PATH, 0);
		baseCount.addListener(example);
		baseCount.start();
		
		List<SharedCount> examples = Lists.newArrayList();
		ExecutorService service = Executors.newFixedThreadPool(QTY);
		for (int i = 0; i < QTY; ++i) {
			final SharedCount count = new SharedCount(client, PATH, 0);
			examples.add(count);
			Callable<Void> task = new Callable<Void>() {
				@Override
				public Void call() throws Exception {
					count.start();
					Thread.sleep(rand.nextInt(10000));
					System.out.println("Increment:" + count.trySetCount(count.getVersionedValue(), count.getCount() + rand.nextInt(10)));
					return null;
				}
			};
			service.submit(task);
		}
		
		
		
		service.shutdown();
		service.awaitTermination(10, TimeUnit.MINUTES);
		
		for (int i = 0; i < QTY; ++i) {
			examples.get(i).close();
		}
		baseCount.close();
	}


}