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.thoughtworks.go.buildsession.ExecCommandExecutor.java

private int executeCommandLine(final BuildSession buildSession, final CommandLine commandLine) {
    final AtomicInteger exitCode = new AtomicInteger(-1);
    final CountDownLatch canceledOrDone = new CountDownLatch(1);
    buildSession.submitRunnable(new Runnable() {
        @Override/*ww w  .  j  a  v  a2 s  .  co  m*/
        public void run() {
            try {
                exitCode.set(commandLine.run(buildSession.processOutputStreamConsumer(), null));
            } catch (CommandLineException e) {
                LOG.error("Command failed", e);
                String message = format(
                        "Error happened while attempting to execute '%s'. \nPlease make sure [%s] can be executed on this agent.\n",
                        commandLine.toStringForDisplay(), commandLine.getExecutable());
                String path = System.getenv("PATH");
                buildSession.println(message);
                buildSession.println(format("[Debug Information] Environment variable PATH: %s", path));
                LOG.error(format("[Command Line] %s. Path: %s", message, path));
            } finally {
                canceledOrDone.countDown();
            }
        }
    });

    Future<?> cancelMonitor = buildSession.submitRunnable(new Runnable() {
        @Override
        public void run() {
            try {
                buildSession.waitUntilCanceled();
            } catch (InterruptedException e) {
                // ignore
            } finally {
                canceledOrDone.countDown();
            }
        }
    });

    try {
        canceledOrDone.await();
    } catch (InterruptedException e) {
        LOG.error("Building thread interrupted", e);
    }
    cancelMonitor.cancel(true);
    return exitCode.get();
}

From source file:example.springdata.cassandra.people.RxJava2PersonRepositoryIntegrationTest.java

/**
 * Result set {@link com.datastax.driver.core.Row}s are converted to entities as they are emitted. Reactive pull and
 * prefetch define the amount of fetched records.
 *///from   w ww . j av  a  2s  .com
@Test
public void shouldPerformConversionBeforeResultProcessing() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    repository.findAll() //
            .doOnNext(System.out::println) //
            .doOnEach(it -> countDownLatch.countDown()) //
            .doOnError(throwable -> countDownLatch.countDown()) //
            .subscribe();

    countDownLatch.await();
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkController.java

@Override
synchronized public void stop() {

    coordinator.release();//from   w  w w .j  av a  2  s  .c o  m
    super.stop();

    log().info("BenchmarkController going down in 5 Seconds");

    final CountDownLatch brokerStopLatch = new CountDownLatch(1);
    final ScheduledThreadPoolExecutor waiter = new ScheduledThreadPoolExecutor(1);
    waiter.schedule(new Runnable() {
        public void run() {
            brokerStopLatch.countDown();
            waiter.shutdown();
        }
    }, 5, TimeUnit.SECONDS);

    try {
        brokerStopLatch.await();
    } catch (InterruptedException e1) {
    }

    if (broker != null) {
        log().info("Stopping embedded broker for Benchmark framework: ");
        try {
            broker.stop();
        } catch (Exception e) {
            // log().error("Embedded broker could not be stopped.", e);
        }
    }
}

From source file:com.alibaba.wasp.master.TestMaster.java

@Test
public void testMasterOpsWhileSplitting() throws Exception {
    MiniWaspCluster cluster = TEST_UTIL.getWaspCluster();
    FMaster m = cluster.getMaster();/*from  w ww. ja  v a 2 s.com*/

    FTable ft = TEST_UTIL.createTable(TABLENAME);
    assertTrue(m.assignmentManager.getZKTable().isEnabledTable(Bytes.toString(TABLENAME)));
    TEST_UTIL.loadTable(ft);

    List<Pair<EntityGroupInfo, ServerName>> tableEntityGroups = FMetaReader
            .getTableEntityGroupsAndLocations(TEST_UTIL.getConfiguration(), TABLENAME);
    LOG.info("EntityGroups after load: " + Joiner.on(',').join(tableEntityGroups));
    assertEquals(1, tableEntityGroups.size());
    assertArrayEquals(FConstants.EMPTY_START_ROW, tableEntityGroups.get(0).getFirst().getStartKey());
    assertArrayEquals(FConstants.EMPTY_END_ROW, tableEntityGroups.get(0).getFirst().getEndKey());

    // Now trigger a split and stop when the split is in progress
    CountDownLatch split = new CountDownLatch(1);
    CountDownLatch proceed = new CountDownLatch(1);
    EntityGroupSplitListener list = new EntityGroupSplitListener(split, proceed);
    cluster.getMaster().executorService.registerListener(EventType.FSERVER_ZK_ENTITYGROUP_SPLIT, list);

    LOG.info("Splitting table");
    TEST_UTIL.getWaspAdmin().split(TABLENAME, Bytes.toBytes("1234"));
    LOG.info("Waiting for split result to be about to open");
    split.await(60, TimeUnit.SECONDS);
    try {
        LOG.info("Making sure we can call getTableEntityGroups while opening");
        tableEntityGroups = FMetaReader.getTableEntityGroupsAndLocations(TEST_UTIL.getConfiguration(),
                TABLENAME, false);

        LOG.info("EntityGroups: " + Joiner.on(',').join(tableEntityGroups));
        // We have three entitygroups because one is split-in-progress
        assertEquals(3, tableEntityGroups.size());
        LOG.info("Making sure we can call getTableEntityGroupClosest while opening");
        Pair<EntityGroupInfo, ServerName> pair = m.getTableEntityGroupForRow(TABLENAME, Bytes.toBytes("cde"));
        LOG.info("Result is: " + pair);
        Pair<EntityGroupInfo, ServerName> tableEntityGroupFromName = FMetaReader
                .getEntityGroup(TEST_UTIL.getConfiguration(), pair.getFirst().getEntityGroupName());
        assertEquals(tableEntityGroupFromName.getFirst(), pair.getFirst());
    } finally {
        proceed.countDown();
    }
}

From source file:io.smartspaces.service.comm.network.NettyUdpSocketTest.java

/**
 * Test a round trip from a UDP client to a UDP server and back.
 *
 * @throws Exception//  w ww  .  j a v  a  2 s.c  om
 *           something bad
 */
@Test
public void testUdpPacketSend() throws Exception {
    final byte[] serverResponseExpectedData = new byte[] { 17, 2, 89, 127 };
    byte[] serverRequestExpectedData = new byte[] { 55, 66, 22, 87 };

    int serverPort = 8099;

    final CountDownLatch serverReceiveLatch = new CountDownLatch(1);
    final AtomicReference<UdpServerRequest> serverRequestActualData = new AtomicReference<UdpServerRequest>();

    final CountDownLatch clientReceiveLatch = new CountDownLatch(1);
    final AtomicReference<byte[]> serverResponseActualData = new AtomicReference<byte[]>();

    UdpServerNetworkCommunicationEndpoint serverEndpoint = serverService.newServer(serverPort, log);
    UdpClientNetworkCommunicationEndpoint clientEndpoint = clientService.newClient(log);

    try {
        serverEndpoint.addListener(new UdpServerNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpRequest(UdpServerNetworkCommunicationEndpoint endpoint, UdpServerRequest request) {
                serverRequestActualData.set(request);

                request.writeResponse(serverResponseExpectedData);

                serverReceiveLatch.countDown();
            }
        });

        serverEndpoint.startup();

        clientEndpoint.addListener(new UdpClientNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpResponse(UdpClientNetworkCommunicationEndpoint endpoint, byte[] response,
                    InetSocketAddress remoteAddress) {
                serverResponseActualData.set(response);

                clientReceiveLatch.countDown();
            }
        });
        clientEndpoint.startup();

        WriteableUdpPacket packet = clientEndpoint.newWriteableUdpPacket(serverRequestExpectedData.length);
        packet.writeBytes(serverRequestExpectedData);

        packet.write(new InetSocketAddress("127.0.0.1", serverPort));

        Assert.assertTrue(clientReceiveLatch.await(5, TimeUnit.SECONDS));
        Assert.assertTrue(serverReceiveLatch.await(5, TimeUnit.SECONDS));
    } finally {
        clientEndpoint.shutdown();
        serverEndpoint.shutdown();
    }

    Assert.assertArrayEquals(serverRequestExpectedData, serverRequestActualData.get().getRequest());
    Assert.assertArrayEquals(serverResponseExpectedData, serverResponseActualData.get());
}

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

@Test(timeout = 60000)
public void updateTest() throws Exception {
    // create message first
    counter = new CountDownLatch(1);
    prepareMessage();/*ww w . jav a  2s. co  m*/
    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 {
                    updateAndCheck();
                } finally {
                    // clean up
                    removeMessage();
                }
            } catch (Throwable t) {
                reportError(t);
            }

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

From source file:com.yahoo.sshd.authentication.file.TestPKUpdating.java

private TestContext setup() throws IOException, InterruptedException {
    TestContext testContext = new TestContext();

    // first build dirs.

    if (homeDir.exists()) {
        FileUtils.forceDelete(homeDir);/*w w  w  .j  a va 2 s . c  o m*/
    }

    FileUtils.forceMkdir(homeDir);

    // build user directories.
    User[] dirs = new User[normalUsers.length + notUsers.length];
    System.arraycopy(normalUsers, 0, dirs, 0, normalUsers.length);
    System.arraycopy(notUsers, 0, dirs, normalUsers.length, notUsers.length);

    buildSshDirs(homeDir, dirs);

    // this point everyone in users has a public key, so we can load it, and
    // check for them.
    CountDownLatch waiter = new CountDownLatch(1);
    testContext.publickeyAuthenticator = new HomeDirectoryScanningPKAuthenticator(waiter, homeDir,
            Arrays.asList(new Path[] { new File(homeDir, "y").toPath() }));
    testContext.publickeyAuthenticator.start();

    waiter.await();

    checkExist(testContext, normalUsers);
    checkDoesntExist(testContext, notUsers);

    return testContext;
}

From source file:com.google.dart.tools.ui.omni.elements.TopLevelElementProvider_NEW.java

@Override
public OmniElement[] getElements(String pattern) {
    if (StringUtils.isBlank(pattern)) {
        return new OmniElement[0];
    }//  w w w.ja v  a 2  s .c  o m
    // initiate a new request, if a new pattern
    if (!StringUtils.equals(currentRequestPattern, pattern)) {
        currentRequestPattern = pattern;
        currentRequestLatch = new CountDownLatch(1);
        doSearch();
        // wait a little, if results are ready quickly
        Uninterruptibles.awaitUninterruptibly(currentRequestLatch, WAIT_MS, TimeUnit.MILLISECONDS);
    }
    // return current results
    synchronized (lock) {
        return results.toArray(new OmniElement[results.size()]);
    }
}

From source file:co.cask.tigon.test.SQLFlowTestBase.java

/**
 * This function is used to add additional error checking by allowing the user to assert on the number of expected
 * output data packets./*from  w w w . java2 s. com*/
 * @param count Number of expected output data packets
 * @return {@link java.util.concurrent.CountDownLatch} object that will count down to zero as output data packets are
 * received
 */
public static CountDownLatch setExpectedOutputCount(int count) {
    latch = new CountDownLatch(count);
    return latch;
}

From source file:io.kamax.mxisd.backend.firebase.GoogleFirebaseAuthenticator.java

@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
    if (!isEnabled()) {
        throw new IllegalStateException();
    }// w  w w  .j  av  a  2 s. c om

    log.info("Trying to authenticate {}", mxid);

    final BackendAuthResult result = BackendAuthResult.failure();

    String localpart = mxid.getLocalPart();
    CountDownLatch l = new CountDownLatch(1);
    getFirebase().verifyIdToken(password).addOnSuccessListener(token -> {
        try {
            if (!StringUtils.equals(localpart, token.getUid())) {
                log.info(
                        "Failure to authenticate {}: Matrix ID localpart '{}' does not match Firebase UID '{}'",
                        mxid, localpart, token.getUid());
                result.fail();
                return;
            }

            result.succeed(mxid.getId(), UserIdType.MatrixID.getId(), token.getName());
            log.info("{} was successfully authenticated", mxid);
            log.info("Fetching profile for {}", mxid);
            CountDownLatch userRecordLatch = new CountDownLatch(1);
            getFirebase().getUser(token.getUid()).addOnSuccessListener(user -> {
                try {
                    toEmail(result, user.getEmail());
                    toMsisdn(result, user.getPhoneNumber());

                    for (UserInfo info : user.getProviderData()) {
                        toEmail(result, info.getEmail());
                        toMsisdn(result, info.getPhoneNumber());
                    }

                    log.info("Got {} 3PIDs in profile", result.getProfile().getThreePids().size());
                } finally {
                    userRecordLatch.countDown();
                }
            }).addOnFailureListener(e -> {
                try {
                    log.warn("Unable to fetch Firebase user profile for {}", mxid);
                    result.fail();
                } finally {
                    userRecordLatch.countDown();
                }
            });

            waitOnLatch(result, userRecordLatch, "Firebase user profile");
        } finally {
            l.countDown();
        }
    }).addOnFailureListener(e -> {
        try {
            if (e instanceof IllegalArgumentException) {
                log.info("Failure to authenticate {}: invalid firebase token", mxid);
            } else {
                log.info("Failure to authenticate {}: {}", mxid, e.getMessage(), e);
                log.info("Exception", e);
            }

            result.fail();
        } finally {
            l.countDown();
        }
    });

    waitOnLatch(result, l, "Firebase auth check");
    return result;
}