Example usage for java.util.concurrent CountDownLatch await

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

Introduction

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

Prototype

public void await() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted .

Usage

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

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining. It prints
 * the two counts ({@code 4} and {@code 6}) to the console.
 *///from www.java  2s.  c  om
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    template.count(Person.class) //
            .doOnNext(System.out::println) //
            .thenMany(Flux.just(new Person("Hank", "Schrader", 43), //
                    new Person("Mike", "Ehrmantraut", 62)))
            .flatMap(template::insert) //
            .last() //
            .flatMap(v -> template.count(Person.class)) //
            .doOnNext(System.out::println) //
            .doOnTerminate(countDownLatch::countDown) //
            .subscribe();

    countDownLatch.await();
}

From source file:forge.CardStorageReader.java

private void executeLoadTask(final Collection<CardRules> result, final List<Callable<List<CardRules>>> tasks,
        final CountDownLatch cdl) {
    try {/*w  w w  .j  av  a 2s  .c  o  m*/
        if (useThreadPool) {
            final ExecutorService executor = ThreadUtil.getComputingPool(0.5f);
            final List<Future<List<CardRules>>> parts = executor.invokeAll(tasks);
            executor.shutdown();
            cdl.await();
            for (final Future<List<CardRules>> pp : parts) {
                result.addAll(pp.get());
            }
        } else {
            for (final Callable<List<CardRules>> c : tasks) {
                result.addAll(c.call());
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } catch (final Exception e) { // this clause comes from non-threaded branch
        throw new RuntimeException(e);
    }
}

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

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 *///  ww  w .  j a  va  2s .  com
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    repository.count() //
            .doOnNext(System.out::println) //
            .thenMany(repository.saveAll(Flux.just(new Person("Hank", "Schrader", 43), //
                    new Person("Mike", "Ehrmantraut", 62)))) //
            .last() //
            .flatMap(v -> repository.count()) //
            .doOnNext(System.out::println) //
            .doOnTerminate(countDownLatch::countDown) //
            .subscribe();

    countDownLatch.await();
}

From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java

/**
 * Pushes the UserProfileModel onto the server
 * @param uPModel/*from w  ww  .j a  v  a2 s.  c  o  m*/
 * @throws InterruptedException
 */
public static void pushUserProfile(final UserProfileModel uPModel) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    if (GSON == null)
        constructGson();

    Thread thread = new Thread() {

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(profileAddress + uPModel.getUniqueID() + "/");

            try {

                request.setEntity(new StringEntity(GSON.toJson(uPModel)));

                HttpResponse response = client.execute(request);
                Log.w(serverName, response.getStatusLine().toString());

                response.getStatusLine().toString();
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String output = reader.readLine();
                while (output != null) {
                    Log.w(serverName, output);
                    output = reader.readLine();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    };
    thread.start();
    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.espertech.esper.dataflow.core.EPDataFlowInstanceImpl.java

public void join() throws InterruptedException {
    if (state == EPDataFlowState.INSTANTIATED) {
        throw new IllegalStateException("Data flow '" + dataFlowName
                + "' instance has not been executed, please use join after start or run");
    }/*  w ww . j  a  v  a  2 s  . c o  m*/
    if (state == EPDataFlowState.CANCELLED) {
        throw new IllegalStateException(
                "Data flow '" + dataFlowName + "' instance has been cancelled and cannot be joined");
    }

    // latch used for non-blocking start
    if (threads != null) {
        for (Thread thread : threads) {
            thread.join();
        }
    } else {
        CountDownLatch latch = new CountDownLatch(1);
        synchronized (this) {
            if (joinedThreadLatches == null) {
                joinedThreadLatches = new ArrayList<CountDownLatch>();
            }
            joinedThreadLatches.add(latch);
        }
        if (state != EPDataFlowState.COMPLETE) {
            latch.await();
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestGroup.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void runTests(List<TestCase> testsToRun, final MobileServiceClient client,
        final TestExecutionCallback callback) {

    try {/*from  ww w  .j a  v a2  s .  co  m*/
        onPreExecute(client);
    } catch (Exception e) {
        mStatus = TestStatus.Failed;
        if (callback != null)
            callback.onTestGroupComplete(this, null);
        return;
    }

    final TestRunStatus testRunStatus = new TestRunStatus();

    mNewTestRun = true;

    int oldQueueSize = mTestRunQueue.size();
    mTestRunQueue.clear();
    mTestRunQueue.addAll(testsToRun);
    cleanTestsState();
    testRunStatus.results.clear();
    mStatus = TestStatus.NotRun;

    if (oldQueueSize == 0) {
        for (final TestCase test : mTestRunQueue) {

            final CountDownLatch latch = new CountDownLatch(1);

            Thread thread = new Thread() {
                public void run() {
                    executeNextTest(test, client, callback, testRunStatus, latch);
                }
            };

            thread.run();

            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (test.getStatus() == TestStatus.Failed) {
                mFailedTestCount++;
            }
        }

        // End Run
        final CountDownLatch latch = new CountDownLatch(1);

        Thread thread = new Thread() {
            public void run() {
                executeNextTest(null, client, callback, testRunStatus, latch);
            }
        };

        thread.run();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.codefollower.lealone.omid.tso.persistence.BookKeeperStateBuilder.java

@Override
public TSOState buildState() throws LoggerException {
    try {//  w  w  w .  j av  a2  s. co  m
        CountDownLatch latch = new CountDownLatch(1);

        zk = new ZooKeeper(config.getZkServers(),
                Integer.parseInt(System.getProperty("SESSIONTIMEOUT", Integer.toString(10000))),
                new LoggerWatcher(latch));

        latch.await();
    } catch (Exception e) {
        LOG.error("Exception while starting zookeeper client", e);
        zk = null;
        throw LoggerException.create(Code.ZKOPFAILED);
    }

    LOG.info("Creating bookkeeper client");

    BookKeeper bk;
    try {
        bk = new BookKeeper(new ClientConfiguration(), zk);
    } catch (Exception e) {
        LOG.error("Exception while creating bookkeeper object", e);
        throw LoggerException.create(Code.BKOPFAILED);
    }

    LOG.info("Creating omid ephemeral ZooKeeper lock path");

    Context ctx = new Context();
    ctx.config = config;
    ctx.bk = bk;

    zk.create(LoggerConstants.OMID_LOCK_PATH, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
            new LockCreateCallback(), ctx);

    LoggerInitCallback callback = new LoggerInitCallback() {
        public void loggerInitComplete(int rc, StateLogger sl, Object ctx) {
            if (rc == Code.OK) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Logger is ok.");
                }
                ((Context) ctx).setLogger(sl);
            } else {
                LOG.error("Error when initializing logger: " + LoggerException.getMessage(rc));
            }
        }
    };

    new BookKeeperStateLogger(zk, bk).initialize(callback, ctx);

    try {
        synchronized (ctx) {
            if (!ctx.isFinished()) {
                // TODO make configurable maximum waiting
                ctx.wait();
            }
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for state to build up.", e);
        ctx.setState(null);
    }

    return ctx.state;
}

From source file:com.predic8.membrane.examples.tests.integration.OAuth2RaceCondition.java

@Test
public void testSessionIdStateRaceCondition() throws Exception {
    HttpClient hc = HttpClientBuilder.create().build();

    login(hc);/*from  w w  w  .  java  2s . co m*/
    System.out.println("Logged in");
    ExecutorService executor = Executors.newFixedThreadPool(2);
    for (int i = 0; i < 10; i++) {

        //            HttpClient hc1 = HttpClientBuilder.create().build();
        //            login(hc1);
        Future<Exception>[] results = new Future[2];

        int parallelReqs = 2;
        CountDownLatch cdl = new CountDownLatch(parallelReqs);

        for (int j = 0; j < parallelReqs; j++) {
            final int fj = j;
            results[j] = executor.submit(() -> {
                try {
                    int uri = (fj % 2 == 0 ? 1 : 2);
                    String url = "http://localhost:2011/test" + uri;
                    HttpGet get = new HttpGet(url);
                    //setNoRedirects(get);
                    cdl.countDown();
                    cdl.await();
                    try (CloseableHttpResponse getRes = (CloseableHttpResponse) hc.execute(get)) {
                        assertEquals(200, getRes.getStatusLine().getStatusCode());
                        String resText = EntityUtils.toString(getRes.getEntity(), "UTF-8");
                        System.out.println("Called: Test" + uri + ".\nActual: " + resText);
                        assertTrue(resText.contains(Integer.toString(uri)));
                    }
                    return null;
                } catch (Exception e) {
                    return e;
                }
            });
        }
        for (int j = 0; j < parallelReqs; j++) {
            results[j].get();
        }

        for (int j = 0; j < parallelReqs; j++) {
            Exception e = results[j].get();
            if (e != null)
                throw new RuntimeException(e);
        }

    }
    executor.shutdown();
}

From source file:com.yahoo.omid.tso.persistence.BookKeeperStateBuilder.java

@Override
public TSOState buildState() throws LoggerException {
    try {//www . j  av  a  2  s.co  m
        CountDownLatch latch = new CountDownLatch(1);

        this.zk = new ZooKeeper(config.getZkServers(),
                Integer.parseInt(System.getProperty("SESSIONTIMEOUT", Integer.toString(10000))),
                new LoggerWatcher(latch));

        latch.await();
    } catch (Exception e) {
        LOG.error("Exception while starting zookeeper client", e);
        this.zk = null;
        throw LoggerException.create(Code.ZKOPFAILED);
    }

    LOG.info("Creating bookkeeper client");

    try {
        bk = new BookKeeper(new ClientConfiguration(), this.zk);
    } catch (Exception e) {
        LOG.error("Error while creating bookkeeper object", e);
        return null;
    }

    /*
     * Create ZooKeeper lock
     */

    Context ctx = new Context();
    ctx.config = this.config;

    zk.create(LoggerConstants.OMID_LOCK_PATH, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
            new LockCreateCallback(), ctx);

    new BookKeeperStateLogger(zk).initialize(new LoggerInitCallback() {
        public void loggerInitComplete(int rc, StateLogger sl, Object ctx) {
            if (rc == Code.OK) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Logger is ok.");
                }
                ((Context) ctx).setLogger(sl);
            } else {
                LOG.error("Error when initializing logger: " + LoggerException.getMessage(rc));
            }
        }

    }, ctx);

    try {
        synchronized (ctx) {
            if (!ctx.isFinished()) {
                // TODO make configurable maximum waiting
                ctx.wait();
            }
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for state to build up.", e);
        ctx.setState(null);
    }

    return ctx.state;
}

From source file:com.brienwheeler.apps.main.ContextMainTest.java

@Test
public void testContextList() throws InterruptedException {
    PropertiesTestUtils.clearAllTestSystemProperties();
    Assert.assertNull(System.getProperty(TestDataConstants.RMAP_TEST_PROP));

    CountDownLatch latch = new CountDownLatch(1);
    TestContextMain main = new TestContextMain(new String[] { C, TestDataConstants.RMAP_CTX_LIST }, latch);
    TestRunner testRunner = new TestRunner(main);
    testRunner.start();/*from  w w w.  j  a  v a 2  s.com*/

    latch.await();

    Assert.assertEquals(TestDataConstants.RMAP_TEST_VAL, System.getProperty(TestDataConstants.RMAP_TEST_PROP));
    assertLaunchCount(main, 2);

    main.shutdown();
    testRunner.join();
}