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.navercorp.pinpoint.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    final MessageConverter<TBase<?, ?>> messageConverter = new BypassMessageConverter<TBase<?, ?>>();
    final MessageSerializer<ByteMessage> thriftMessageSerializer = new ThriftUdpMessageSerializer(
            messageConverter, ThriftUdpMessageSerializer.UDP_MAX_PACKET_LENGTH) {
        @Override/*  w w w  .  j  a v  a  2s.  co  m*/
        protected boolean isLimit(int interBufferSize) {
            final boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };

    UdpDataSender sender = new UdpDataSender("localhost", PORT, "test", 128, 1000, 1024 * 64 * 100,
            thriftMessageSerializer);
    try {
        sender.send(tbase);
        latch.await(waitTimeMillis, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

From source file:com.twitter.hbc.httpclient.BasicClientTest.java

@Test
public void testIOExceptionDuringProcessing() throws Exception {
    ClientBase clientBase = new ClientBase("name", mockClient, new HttpHosts("http://hi"),
            new RawEndpoint("/endpoint", HttpConstants.HTTP_GET), mockAuth, mockProcessor,
            mockReconnectionManager, mockRateTracker);
    BasicClient client = new BasicClient(clientBase, executorService);
    final CountDownLatch latch = new CountDownLatch(1);
    when(mockStatusLine.getStatusCode()).thenReturn(200);

    doNothing().when(mockProcessor).setup(any(InputStream.class));
    doThrow(new IOException()).doThrow(new IOException()).doThrow(new IOException()).doAnswer(new Answer() {
        @Override//w w w. j a  v  a  2 s. c  o m
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            latch.countDown();
            return null;
        }
    }).when(mockProcessor).process();

    client.connect();
    latch.await();
    assertFalse(clientBase.isDone());
    verify(mockProcessor, times(4)).setup(any(InputStream.class));
    // throw 3 exceptions, 4th one keeps going
    verify(mockProcessor, atLeast(4)).process();

    client.stop();
    verify(mockConnectionManager, atLeastOnce()).shutdown();
    assertTrue(client.isDone());
    assertEquals(EventType.STOPPED_BY_USER, clientBase.getExitEvent().getEventType());
}

From source file:dstrelec.nats.listener.DefaultNatsListenerContainer.java

@Override
public final void stop() {
    final CountDownLatch latch = new CountDownLatch(1);
    stop(new Runnable() {
        @Override//from  w  ww  .  j a v  a2 s.  com
        public void run() {
            latch.countDown();
        }
    });
    try {
        latch.await(this.containerProperties.getShutdownTimeout(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        //
    }
}

From source file:com.ottogroup.bi.streaming.runtime.StreamingAppRuntimeTest.java

/**
 * Test case for {@link StreamingAppRuntime#parseCommandLine(String[])} being
 * provided an array showing unknown settings
 *///w  w  w .j a va 2 s .  c o  m
@Test(expected = UnrecognizedOptionException.class)
public void testParseCommandLine_withUnknownSettings() throws Exception {
    new DummyLogProcessingRuntime(new CountDownLatch(1)).parseCommandLine(new String[] { "-a", "123" });
}

From source file:io.opentracing.contrib.elasticsearch5.TracingTest.java

@Test
public void restClient() throws Exception {
    RestClient restClient = RestClient.builder(new HttpHost("localhost", HTTP_PORT, "http"))
            .setHttpClientConfigCallback(new TracingHttpClientConfigCallback(mockTracer)).build();

    HttpEntity entity = new NStringEntity(
            "{\n" + "    \"user\" : \"kimchy\",\n" + "    \"post_date\" : \"2009-11-15T14:12:12\",\n"
                    + "    \"message\" : \"trying out Elasticsearch\"\n" + "}",
            ContentType.APPLICATION_JSON);

    Response indexResponse = restClient.performRequest("PUT", "/twitter/tweet/1",
            Collections.<String, String>emptyMap(), entity);

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

    final CountDownLatch latch = new CountDownLatch(1);
    restClient.performRequestAsync("PUT", "/twitter/tweet/2", Collections.<String, String>emptyMap(), entity,
            new ResponseListener() {
                @Override
                public void onSuccess(Response response) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    latch.countDown();
                }
            });

    latch.await(30, TimeUnit.SECONDS);
    restClient.close();

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(2, finishedSpans.size());
    checkSpans(finishedSpans, "PUT");
    assertNull(mockTracer.activeSpan());
}

From source file:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java

@Test
public void testGetFabricNodeState() throws IOException, InterruptedException {
    final FabricNodeState mockResponse = new FabricNodeState();
    mockResponse.setState(com.vmware.photon.controller.nsxclient.datatypes.FabricNodeState.SUCCESS);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getFabricNodeState("nodeId",
            new com.google.common.util.concurrent.FutureCallback<FabricNodeState>() {
                @Override/*from w ww. j a va 2s. c om*/
                public void onSuccess(FabricNodeState result) {
                    assertEquals(result, mockResponse);
                    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.socialize.test.integration.services.b.TwitterUtilsTest.java

public void test_link() throws Throwable {

    final CountDownLatch latch = new CountDownLatch(1);
    final Activity context = TestUtils.getActivity(this);

    // Stub in the TwitterAuthProvider
    TwitterAuthProvider mockTwitterAuthProvider = new TwitterAuthProvider() {
        @Override//from w  w  w.j  a  va  2  s  . c o m
        public void authenticate(Context context, TwitterAuthProviderInfo info, AuthProviderListener listener) {
            addResult(0, info);
            latch.countDown();
        }
    };

    SocializeIOC.registerStub("twitterProvider", mockTwitterAuthProvider);

    // Set a mock key/secret
    TwitterUtils.setCredentials(TestUtils.getActivity(this), "foo", "bar");

    // Ensure we don't have a session
    TwitterUtils.unlink(TestUtils.getActivity(this));

    // Validate
    assertFalse(TwitterUtils.isLinked(getContext()));

    // Now Link
    TwitterUtils.link(context, null);

    latch.await(10, TimeUnit.SECONDS);

    TwitterAuthProviderInfo data = getResult(0);

    assertNotNull(data);
    assertEquals(AuthProviderType.TWITTER, data.getType());

    assertEquals("foo", data.getConsumerKey());
    assertEquals("bar", data.getConsumerSecret());

    SocializeIOC.unregisterStub("twitterProvider");
}

From source file:com.basho.riak.client.http.util.logging.ConcurrentLoggingTest.java

/**
 * Test method for/*from ww  w .  j av  a  2s  .co m*/
 * {@link com.basho.riak.client.http.util.logging.LogNoHttpResponseRetryHandler#retryMethod(org.apache.commons.httpclient.HttpMethod, java.io.IOException, int)}
 * .
 * 
 * @throws InterruptedException
 */
@Test
public void retry_concurrentLogAndDump() throws InterruptedException {
    // create a bunch of threads
    // each must log 10 statements and call flush
    // ALL the statements must be present BUT ONCE in
    // the mock delegate appender (order does not matter)
    final int numThreads = 10;
    final LogNoHttpResponseRetryHandler handler = new LogNoHttpResponseRetryHandler();
    ExecutorService es = Executors.newFixedThreadPool(numThreads);
    List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(numThreads);

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch dumpLatch = new CountDownLatch(10);

    for (int i = 0; i < numThreads; i++) {
        final int threadCounter = i;
        tasks.add(new Callable<Void>() {

            @Override
            public Void call() {
                Logger logger = Logger.getLogger("httpclient.wire");
                try {
                    startLatch.await();

                    for (int j = 0; j < 10; j++) {
                        logger.debug(String.format(MESSAGE, new Object[] { threadCounter, j }));
                    }

                    dumpLatch.countDown();
                    dumpLatch.await();

                    handler.retryMethod(new GetMethod(), new NoHttpResponseException(), 0);

                    return null;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    startLatch.countDown();
    es.invokeAll(tasks);

    verify(mockLogger, times(100)).callAppenders(logEventCaptor.capture());

    TreeSet<Integer> check = new TreeSet<Integer>();

    for (LoggingEvent le : logEventCaptor.getAllValues()) {
        // verify that each of Thread:Iter is present for 0-90-9
        int loc = Integer.parseInt(le.getMessage().toString());
        check.add(loc);
    }

    assertEquals(100, check.size());
    assertEquals(0, (int) check.first());
    assertEquals(99, (int) check.last());
}

From source file:com.microsoft.office.integration.test.FoldersAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeFolder();/*w ww .  j  a va2s  .  c o  m*/
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getFolders().getAsync(folder.getId()), new FutureCallback<IFolder>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(IFolder result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:com.example.android.vault.EncryptedDocumentTest.java

private void testMetadataAndContents(byte[] content) throws Exception {
    final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey);
    final byte[] beforeContent = content;

    final ParcelFileDescriptor[] beforePipe = ParcelFileDescriptor.createReliablePipe();
    new Thread() {
        @Override/*from w  w  w.  j a v a  2s  . c om*/
        public void run() {
            final FileOutputStream os = new FileOutputStream(beforePipe[1].getFileDescriptor());
            try {
                os.write(beforeContent);
                beforePipe[1].close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }.start();

    // fully write metadata and content
    final JSONObject before = new JSONObject();
    before.put("meow", "cake");
    doc.writeMetadataAndContent(before, beforePipe[0]);

    // now go back and verify we can read
    final JSONObject after = doc.readMetadata();
    assertEquals("cake", after.getString("meow"));

    final CountDownLatch latch = new CountDownLatch(1);
    final ParcelFileDescriptor[] afterPipe = ParcelFileDescriptor.createReliablePipe();
    final byte[] afterContent = new byte[beforeContent.length];
    new Thread() {
        @Override
        public void run() {
            final FileInputStream is = new FileInputStream(afterPipe[0].getFileDescriptor());
            try {
                int i = 0;
                while (i < afterContent.length) {
                    int n = is.read(afterContent, i, afterContent.length - i);
                    i += n;
                }
                afterPipe[0].close();
                latch.countDown();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }.start();

    doc.readContent(afterPipe[1]);
    latch.await(5, TimeUnit.SECONDS);

    MoreAsserts.assertEquals(beforeContent, afterContent);
}