Example usage for org.apache.hadoop.io.retry RetryPolicy RetryPolicy

List of usage examples for org.apache.hadoop.io.retry RetryPolicy RetryPolicy

Introduction

In this page you can find the example usage for org.apache.hadoop.io.retry RetryPolicy RetryPolicy.

Prototype

RetryPolicy

Source Link

Usage

From source file:com.proofpoint.zookeeper.TestZookeeperClient.java

License:Apache License

@Test
public void testRetries() throws Exception {
    ZookeeperTestServerInstance testServer = new ZookeeperTestServerInstance();

    final AtomicInteger retryCount = new AtomicInteger(0);
    Map<String, String> props = Maps.newHashMap();
    props.put("zookeeper.connection-string", testServer.getConnectString());
    ConfigurationFactory factory = new ConfigurationFactory(props);
    ZookeeperClientConfig zookeeperClientConfig = factory.build(ZookeeperClientConfig.class);
    zookeeperClientConfig.setConnectionTimeoutInMs(1000);

    ZookeeperClient client = new ZookeeperClient(zookeeperClientConfig).setRetryPolicy(new RetryPolicy() {
        @Override//from  ww w .ja  va2 s . c  o  m
        public boolean shouldRetry(Exception e, int retries) throws Exception {
            retryCount.incrementAndGet();
            return retries < 1;
        }
    });
    client.exists("/"); // blocks until connection is achieved

    final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>(new CountDownLatch(1));
    client.setErrorHandler(new ZookeeperClientErrorHandler() {
        @Override
        public void connectionLost(ZookeeperClient client) {
            latch.get().countDown();
        }
    });

    testServer.close(); // next client call causes a retry

    try {
        client.exists("/");
        fail();
    } catch (Exception e) {
        // correct
    }
    assertEquals(retryCount.get(), 2);
    Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS));

    latch.set(new CountDownLatch(1));
    retryCount.set(0);

    // now try with a background call that should succeed

    testServer = new ZookeeperTestServerInstance();
    zookeeperClientConfig.setConnectionString(testServer.getConnectString());

    client.inBackground("").exists("/");
    assertEquals(retryCount.get(), 0);
    assertEquals(latch.get().getCount(), 1);

    client.closeForShutdown();
}