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:com.hp.autonomy.hod.client.api.HavenOnDemandServiceITCase.java

@Test
public void testAsyncPostWithTimeout() throws HodErrorException, InterruptedException {
    final Document document = new Document.Builder().setReference("0e5ed498-7251-4acf-8658-34ed874ca352")
            .setTitle("Some stuff").setContent("").build();

    final Documents<Document> documents = new Documents<>(document);

    final Map<String, Object> params = new HashMap<>();
    params.put("json", documents);
    params.put("duplicate_mode", AddToTextIndexRequestBuilder.DuplicateMode.replace);

    final JobId jobId = havenOnDemandService.postAsync(getTokenProxy(), "textindex",
            getPrivateIndex().toString(), "document", 1, params);

    final CountDownLatch latch = new CountDownLatch(1);
    final TestCallback<Map<String, Object>> testCallback = new TestCallback<>(latch);
    final Runnable runnable = new PollingJobStatusRunnable<>(getTokenProxy(), new Duration(1), jobId,
            testCallback, scheduledExecutorService, jobService);

    scheduledExecutorService.submit(runnable);

    latch.await();

    assertTrue(testCallback.isTimedOut());
    assertThat(testCallback.getResult(), nullValue());
}

From source file:sk.datalan.solr.impl.ConcurrentUpdateSolrServer.java

@Override
public NamedList<Object> request(final SolrRequest request) throws SolrServerException, IOException {
    if (!(request instanceof UpdateRequest)) {
        return server.request(request);
    }//from w  ww. ja  v  a2 s .  c o  m
    UpdateRequest req = (UpdateRequest) request;

    // this happens for commit...
    if (streamDeletes) {
        if ((req.getDocuments() == null || req.getDocuments().isEmpty())
                && (req.getDeleteById() == null || req.getDeleteById().isEmpty())
                && (req.getDeleteByIdMap() == null || req.getDeleteByIdMap().isEmpty())) {
            if (req.getDeleteQuery() == null) {
                blockUntilFinished();
                return server.request(request);
            }
        }
    } else {
        if ((req.getDocuments() == null || req.getDocuments().isEmpty())) {
            blockUntilFinished();
            return server.request(request);
        }
    }

    SolrParams params = req.getParams();
    if (params != null) {
        // check if it is waiting for the searcher
        if (params.getBool(UpdateParams.WAIT_SEARCHER, false)) {
            log.info("blocking for commit/optimize");
            blockUntilFinished(); // empty the queue
            return server.request(request);
        }
    }

    try {
        CountDownLatch tmpLock = lock;
        if (tmpLock != null) {
            tmpLock.await();
        }

        boolean success = queue.offer(req);

        for (;;) {
            synchronized (runners) {
                if (runners.isEmpty() || (queue.remainingCapacity() < queue.size() // queue
                        // is
                        // half
                        // full
                        // and
                        // we
                        // can
                        // add
                        // more
                        // runners
                        && runners.size() < threadCount)) {
                    // We need more runners, so start a new one.
                    Runner r = new Runner();
                    runners.add(r);
                    scheduler.execute(r);
                } else {
                    // break out of the retry loop if we added the element to the queue
                    // successfully, *and*
                    // while we are still holding the runners lock to prevent race
                    // conditions.
                    if (success)
                        break;
                }
            }

            // Retry to add to the queue w/o the runners lock held (else we risk
            // temporary deadlock)
            // This retry could also fail because
            // 1) existing runners were not able to take off any new elements in the
            // queue
            // 2) the queue was filled back up since our last try
            // If we succeed, the queue may have been completely emptied, and all
            // runners stopped.
            // In all cases, we should loop back to the top to see if we need to
            // start more runners.
            //
            if (!success) {
                success = queue.offer(req, 100, TimeUnit.MILLISECONDS);
            }

        }

    } catch (InterruptedException e) {
        log.error("interrupted", e);
        throw new IOException(e.getLocalizedMessage());
    }

    // RETURN A DUMMY result
    NamedList<Object> dummy = new NamedList<>();
    dummy.add("NOTE", "the request is processed in a background stream");
    return dummy;
}

From source file:com.github.sdbg.core.test.util.PlainTestProject.java

/**
 * Disposes allocated resources and deletes project.
 */// w w  w  . j  av  a  2 s .co  m
public void dispose() throws Exception {
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();

    final CountDownLatch latch = new CountDownLatch(1);

    try {
        workspace.run(new IWorkspaceRunnable() {
            @Override
            public void run(IProgressMonitor monitor) throws CoreException {
                TestUtilities.deleteProject(project);
                latch.countDown();
            }
        }, null);
    } finally {
        latch.countDown();
    }

    latch.await();
}

From source file:com.onyxscheduler.domain.SchedulerIT.java

@Test(timeout = FIRE_THRESHOLD_TIMEOUT_IN_MILLIS)
public void shouldFireMultipleTimesWithCron() throws Scheduler.DuplicateJobKeyException, InterruptedException {
    CountDownLatch latch = new CountDownLatch(2);
    latchProvider.setLatch(latch);/* w  w  w  .j ava 2  s .  c om*/
    CountDownJob job = buildEvery2SecondsCronJob();

    scheduler.scheduleJob(job);

    latch.await();
}

From source file:info.archinnov.achilles.it.TestAsyncCRUDSimpleEntity.java

@Test
public void should_insert_async() throws Exception {
    //Given//ww  w.  j a  v  a  2 s .  c  o  m
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final Date date = new Date();
    final SimpleEntity entity = new SimpleEntity(id, date, "value");
    final CountDownLatch latch = new CountDownLatch(1);
    final CassandraLogAsserter logAsserter = new CassandraLogAsserter();
    logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n");

    //When
    manager.crud().insert(entity).withResultSetAsyncListener(rs -> {
        LOGGER.info(CALLED);
        latch.countDown();
        return rs;
    }).executeAsync();

    //Then
    latch.await();
    logAsserter.assertContains("Called - [achilles-default-executor");

    final List<Row> rows = session.execute("SELECT * FROM simple WHERE id = " + id).all();
    assertThat(rows).hasSize(1);

    final Row row = rows.get(0);
    assertThat(row.getLong("id")).isEqualTo(id);
    assertThat(row.getTimestamp("date")).isEqualTo(date);
    assertThat(row.getString("value")).isEqualTo("value");
}

From source file:com.hp.autonomy.hod.client.api.HavenOnDemandServiceITCase.java

@Test
public void testAsyncPostWithJobStatus() throws HodErrorException, InterruptedException {
    final Document document = new Document.Builder().setReference("0e5ed498-7251-4acf-8658-34ed874ca352")
            .setTitle("Some stuff").setContent("").build();

    final Documents<Document> documents = new Documents<>(document);

    final Map<String, Object> params = new HashMap<>();
    params.put("json", documents);
    params.put("duplicate_mode", AddToTextIndexRequestBuilder.DuplicateMode.replace);

    final JobId jobId = havenOnDemandService.postAsync(getTokenProxy(), "textindex",
            getPrivateIndex().toString(), "document", 1, params);

    final CountDownLatch latch = new CountDownLatch(1);
    final TestCallback<Map<String, Object>> testCallback = new TestCallback<>(latch);
    final Runnable runnable = new PollingJobStatusRunnable<>(getTokenProxy(), new Duration(100000), jobId,
            testCallback, scheduledExecutorService, jobService);

    scheduledExecutorService.submit(runnable);

    latch.await();

    final Map<String, Object> result = testCallback.getResult();

    assertThat(result.get("references"), is(notNullValue()));
    assertThat(result.get("references"), is(instanceOf(List.class)));

    @SuppressWarnings("unchecked")
    final List<Map<String, Object>> resultList = (List<Map<String, Object>>) result.get("references");

    assertThat(resultList, hasSize(1));//from  w ww . j av  a2  s .  c o m
}

From source file:com.alibaba.otter.node.etl.load.WeightControllerTest.java

@Test
public void test_simple() {
    int thread = 10;
    int count = 10;
    WeightController controller = new WeightController(thread);
    CountDownLatch latch = new CountDownLatch(thread);
    WeightWorkerTest[] workers = new WeightWorkerTest[thread];
    for (int i = 0; i < thread; i++) {
        int[] weights = new int[count];
        for (int j = 0; j < count; j++) {
            weights[j] = RandomUtils.nextInt(count);
        }// www . j  a v a2  s .c o  m
        workers[i] = new WeightWorkerTest(i, weights, controller, latch);
    }

    for (int i = 0; i < thread; i++) {
        workers[i].start();
    }

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

From source file:org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer.java

@Override
public NamedList<Object> request(final SolrRequest request) throws SolrServerException, IOException {
    if (!(request instanceof UpdateRequest)) {
        return server.request(request);
    }/* w  w  w.ja v  a 2  s .  c o m*/
    UpdateRequest req = (UpdateRequest) request;

    // this happens for commit...
    if (streamDeletes) {
        if ((req.getDocuments() == null || req.getDocuments().isEmpty())
                && (req.getDeleteById() == null || req.getDeleteById().isEmpty())
                && (req.getDeleteByIdMap() == null || req.getDeleteByIdMap().isEmpty())) {
            if (req.getDeleteQuery() == null) {
                blockUntilFinished();
                return server.request(request);
            }
        }
    } else {
        if ((req.getDocuments() == null || req.getDocuments().isEmpty())) {
            blockUntilFinished();
            return server.request(request);
        }
    }

    SolrParams params = req.getParams();
    if (params != null) {
        // check if it is waiting for the searcher
        if (params.getBool(UpdateParams.WAIT_SEARCHER, false)) {
            log.info("blocking for commit/optimize");
            blockUntilFinished(); // empty the queue
            return server.request(request);
        }
    }

    try {
        CountDownLatch tmpLock = lock;
        if (tmpLock != null) {
            tmpLock.await();
        }

        boolean success = queue.offer(req);

        for (;;) {
            synchronized (runners) {
                // see if queue is half full and we can add more runners
                // special case: if only using a threadCount of 1 and the queue
                // is filling up, allow 1 add'l runner to help process the queue
                if (runners.isEmpty()
                        || (queue.remainingCapacity() < queue.size() && runners.size() < threadCount)) {
                    // We need more runners, so start a new one.
                    Runner r = new Runner();
                    runners.add(r);
                    scheduler.execute(r);
                } else {
                    // break out of the retry loop if we added the element to the queue
                    // successfully, *and*
                    // while we are still holding the runners lock to prevent race
                    // conditions.
                    if (success)
                        break;
                }
            }

            // Retry to add to the queue w/o the runners lock held (else we risk
            // temporary deadlock)
            // This retry could also fail because
            // 1) existing runners were not able to take off any new elements in the
            // queue
            // 2) the queue was filled back up since our last try
            // If we succeed, the queue may have been completely emptied, and all
            // runners stopped.
            // In all cases, we should loop back to the top to see if we need to
            // start more runners.
            //
            if (!success) {
                success = queue.offer(req, 100, TimeUnit.MILLISECONDS);
            }
        }
    } catch (InterruptedException e) {
        log.error("interrupted", e);
        throw new IOException(e.getLocalizedMessage());
    }

    // RETURN A DUMMY result
    NamedList<Object> dummy = new NamedList<>();
    dummy.add("NOTE", "the request is processed in a background stream");
    return dummy;
}

From source file:com.smartnsoft.hackathon.directenergie.ws.NetatmoServices.java

public List<Station> getDevicesList() throws InterruptedException {

    final CountDownLatch deviceWait = new CountDownLatch(1);
    deviceWait.countDown();//from   www  .j a va 2  s .c o  m
    getDevicesList(new NetatmoResponseHandler(NetatmoServices.this,
            NetatmoResponseHandler.REQUEST_GET_DEVICES_LIST, null) {
        @Override
        public void onGetDevicesListResponse(final List<Station> devices) {
            devicesList = devices;
            try {
                deviceWait.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    return devicesList;
    //    synchronized (devicesList)
    //    {
    //      getDevicesList(new NetatmoResponseHandler(NetatmoServices.this, NetatmoResponseHandler.REQUEST_GET_DEVICES_LIST, null)
    //      {
    //        @Override
    //        public void onGetDevicesListResponse(final List<Station> devices)
    //        {
    //          devicesList = devices;
    //        }
    //      });
    //      return devicesList;
    //    }
}

From source file:com.flipkart.flux.deploymentunit.ExecutableRegistryPopulator.java

@Override
public void initialize() {

    //count down latch to parallelly populate executable registry from multiple deployment units
    CountDownLatch duCountDownLatch = new CountDownLatch(deploymentUnitsMap.size());

    //for each deployment unit, start a new thread which populates executable registry
    for (Map.Entry<String, DeploymentUnit> deploymentUnitEntry : deploymentUnitsMap.entrySet()) {
        new Thread(new ExecutableRegistryLoader(deploymentUnitEntry.getKey(), deploymentUnitEntry.getValue(),
                duCountDownLatch)).start();
    }/*w w  w . j a  va  2s  .c om*/

    try {
        duCountDownLatch.await(); //wait until all deployment units' tasks are loaded into executable registry
    } catch (InterruptedException e) {
        LOGGER.error(
                "Unable to populate executable registry. Deployment unit count down latch has been interrupted. Exception: {}",
                e.getMessage());
        throw new FluxError(FluxError.ErrorType.runtime,
                "Unable to populate executable registry. Deployment unit count down latch has been interrupted.",
                e);
    }
}