Example usage for java.util.concurrent CountDownLatch CountDownLatch

List of usage examples for java.util.concurrent CountDownLatch CountDownLatch

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch CountDownLatch.

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

From source file:com.vmware.photon.controller.api.client.resource.DisksApiTest.java

@Test
public void testGetDiskAsync() throws IOException, InterruptedException {
    final PersistentDisk persistentDisk = new PersistentDisk();
    persistentDisk.setId("persistentDisk");

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(persistentDisk);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    DisksApi disksApi = new DisksApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    disksApi.getDiskAsync("disk1", new FutureCallback<PersistentDisk>() {
        @Override/*from  w w  w  . ja va  2s. c  o m*/
        public void onSuccess(@Nullable PersistentDisk result) {
            assertEquals(result, persistentDisk);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.api.client.resource.ResourceTicketApiTest.java

@Test
public void testGetResourceTicketAsync() throws IOException, InterruptedException {
    final ResourceTicket resourceTicket1 = new ResourceTicket();
    resourceTicket1.setId("resourceTicket1");

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(resourceTicket1);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ResourceTicketApi resourceTicketApi = new ResourceTicketApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    resourceTicketApi.getResourceTicketAsync("foo", new FutureCallback<ResourceTicket>() {
        @Override/*  ww  w. ja v a 2 s  . c  om*/
        public void onSuccess(@Nullable ResourceTicket result) {
            assertEquals(result, resourceTicket1);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
    ;
}

From source file:com.vmware.photon.controller.api.client.resource.DisksRestApiTest.java

@Test
public void testGetDiskAsync() throws IOException, InterruptedException {
    final PersistentDisk persistentDisk = new PersistentDisk();
    persistentDisk.setId("persistentDisk");

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(persistentDisk);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    DisksApi disksApi = new DisksRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    disksApi.getDiskAsync("disk1", new FutureCallback<PersistentDisk>() {
        @Override/*from   w  w  w  .  j  a va 2  s  .c om*/
        public void onSuccess(@Nullable PersistentDisk result) {
            assertEquals(result, persistentDisk);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java

@Test
public void testPostInitializedForEmpty() throws Exception {
    Timing timing = new Timing();
    PathChildrenCache cache = null;/*from   www .java2  s  . c  om*/
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        cache = new PathChildrenCache(client, "/test", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.INITIALIZED) {
                    latch.countDown();
                }
            }
        });
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        Assert.assertTrue(timing.awaitLatch(latch));
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.vmware.photon.controller.api.client.resource.ResourceTicketRestApiTest.java

@Test
public void testGetResourceTicketAsync() throws IOException, InterruptedException {
    final ResourceTicket resourceTicket1 = new ResourceTicket();
    resourceTicket1.setId("resourceTicket1");

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(resourceTicket1);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ResourceTicketApi resourceTicketApi = new ResourceTicketRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    resourceTicketApi.getResourceTicketAsync("foo", new FutureCallback<ResourceTicket>() {
        @Override// ww  w  .  ja  va  2  s .  c o m
        public void onSuccess(@Nullable ResourceTicket result) {
            assertEquals(result, resourceTicket1);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
    ;
}

From source file:com.adaptris.core.jms.ActiveJmsConnectionErrorHandler.java

@Override
public void init() throws CoreException {
    super.init();
    try {/*from  w  ww .  ja va 2  s  . c  om*/
        MyExceptionHandler handler = new MyExceptionHandler();
        CountDownLatch verifierThreadGate = new CountDownLatch(1);
        verifier = new JmsConnectionVerifier(idForLogging, verifierThreadGate);
        Thread verifierThread = new ManagedThreadFactory(getClass().getSimpleName()).newThread(verifier);
        verifierThread.setName("JmsConnectionErrorHandler for " + idForLogging);
        verifierThread.setUncaughtExceptionHandler(handler);
        verifierThread.start();
        boolean actuallyStarted = verifierThreadGate.await(DEFAULT_MAX_WAIT_FOR_START.toMilliseconds(),
                TimeUnit.MILLISECONDS);
        if (!actuallyStarted) {
            if (handler.hasError()) {
                ExceptionHelper.rethrowCoreException(handler.lastCaughtException);
            } else {
                throw new CoreException("Failed to start connection error handler");
            }
        }
        if (additionalLogging()) {
            log.debug("ActiveJmsConnectionErrorHandler for {} started", idForLogging);
        }
    } catch (Exception e) {
        ExceptionHelper.rethrowCoreException(e);
    }
}

From source file:com.baidu.oped.apm.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);

    UdpDataSender sender = new UdpDataSender("localhost", 9009, "test", 128, 1000, 1024 * 64 * 100) {
        @Override//from   ww  w. j  a  v a2 s  .c om
        protected boolean isLimit(int interBufferSize) {
            boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };
    try {
        sender.send(tbase);
        latch.await(5000, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

From source file:org.cleverbus.core.common.asynch.msg.MessageOperationServiceTest.java

@Test
public void testRestartForFailedMessage_multiThreaded() throws Exception {
    // prepare message in FAILED state
    final Message[] messages = createAndSaveMessages(1, new MessageProcessor() {
        @Override// w w w  .  ja  v  a 2s  .c om
        public void process(Message message) {
            message.setState(MsgStateEnum.FAILED);
        }
    });

    // prepare threads
    int threads = 2;
    final CountDownLatch latch = new CountDownLatch(threads);
    Runnable task = new Runnable() {

        @Override
        public void run() {
            try {
                // cancel message
                operationService.restartMessage(messages[0].getMsgId(), false);
            } finally {
                latch.countDown();
            }
        }
    };

    // start processing and waits for result
    for (int i = 0; i < threads; i++) {
        new Thread(task).start();
    }

    latch.await();

    // verify
    Message msgDB = em.find(Message.class, messages[0].getMsgId());
    assertThat(msgDB, notNullValue());
    assertThat(msgDB.getState(), is(MsgStateEnum.PARTLY_FAILED));
}

From source file:com.microsoft.office.core.MessagesAsyncTestCase.java

@Test(timeout = 60000)
public void readTest() throws Exception {
    // create message first
    prepareMessage();/*from  ww w. j a  va2s .c o  m*/
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                try {
                    readAndCheck();
                } finally {
                    // clean-up
                    removeMessage();
                }
            } catch (Exception e) {
                reportError(e);
            }

            counter.countDown();
        }
    });
    counter.await();
}

From source file:com.twotoasters.android.hoottestapplication.test.HootTest.java

public void testGet() {
    final CountDownLatch latch = new CountDownLatch(1);
    final HootDeserializer<Get> deserializer = new TestHootDeserializer<Get>(Get.class);
    final HootRequest request = mHootRestClient.createRequest().get().setDeserializer(deserializer)
            .bindListener(new TestHootListener(latch, true));

    assertNotNull(request);/* w  ww. j a v  a 2  s .  c  o m*/

    executeTest(request, latch);

    assertTrue(request.getResult() != null && request.getResult().isSuccess()
            && request.getResult().getDeserializedResult() != null
            && deserializer.getDeserializedResult().test.equals("This is a test"));
}