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:gda.util.persistence.LocalParametersTest.java

public void testThreadSafety() throws Exception {
    final File testScratchDir = TestUtils.createClassScratchDirectory(LocalParametersTest.class);
    final String configDir = testScratchDir.getAbsolutePath();

    final String configName = "threadsafety";

    // Delete config from disk, if it exists
    final File configFile = new File(configDir, configName + ".xml");
    configFile.delete();/*  w  w  w.jav  a  2s. com*/

    final AtomicReference<Exception> error = new AtomicReference<Exception>();

    final int numThreads = 4;
    final long threadRunTimeInMs = 5000;
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishLatch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        Thread t = new Thread() {
            @Override
            public void run() {

                try {
                    final FileConfiguration config = LocalParameters.getThreadSafeXmlConfiguration(configDir,
                            configName, true);

                    // Wait for signal to start
                    startLatch.await();

                    final String propertyName = Thread.currentThread().getName();

                    final long startTime = System.currentTimeMillis();
                    while (true) {

                        // Finish if we've exceeded the run time
                        long elapsedTime = System.currentTimeMillis() - startTime;
                        if (elapsedTime >= threadRunTimeInMs) {
                            break;
                        }

                        // Finish if another thread has generated an exception
                        if (error.get() != null) {
                            break;
                        }

                        config.setProperty(propertyName, System.currentTimeMillis());
                        config.save();
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                    error.set(e);
                }

                finishLatch.countDown();
            }
        };
        t.start();
    }

    // Start all threads
    final long startTime = System.currentTimeMillis();
    startLatch.countDown();

    // Wait for all threads to finish
    finishLatch.await();
    final long endTime = System.currentTimeMillis();
    final long elapsedTime = (endTime - startTime);
    System.out.printf("Finished after %dms%n", elapsedTime);

    // No error should have been thrown
    assertNull("An exception was thrown by one of the threads", error.get());
}

From source file:io.smartspaces.master.server.services.internal.comm.StandardMasterRosContext.java

@Override
public void startup() {
    log.info("Starting up the Smart Spaces Master ROS context");

    startupLatch = new CountDownLatch(1);

    if (spaceEnvironment.getSystemConfiguration().getPropertyBoolean(CONFIGURATION_NAME_ROS_MASTER_ENABLE,
            CONFIGURATION_VALUE_DEFAULT_ROS_MASTER_ENABLE)) {
        startupRosMasterController();//from   ww w . ja  v a  2  s . c  om
    }

    log.info("The Smart Spaces Master ROS context is started up");
}

From source file:com.vladmihalcea.mongo.dao.ProductRepositoryIT.java

@Test
public void testRetries() throws InterruptedException {
    Product product = new Product();
    product.setId(123L);//from w w w  .j a  va 2 s  . co m
    product.setName("Tv");
    productRepository.save(product);
    Product savedProduct = productRepository.findOne(123L);
    assertEquals(savedProduct, product);

    final int threadsNumber = 10;

    final AtomicInteger atomicInteger = new AtomicInteger();
    final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1);
    final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1);

    for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) {
        final long index = (long) atomicInteger.get() * threadsNumber;
        LOGGER.info("Scheduling thread index {}", index);
        Thread testThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(123L, UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.error("Exception thrown!", e);
                } finally {
                    endLatch.countDown();
                }
            }
        });
        testThread.start();
    }
    startLatch.countDown();
    LOGGER.info("Waiting for threads to be done");
    endLatch.countDown();
    endLatch.await();
    LOGGER.info("Threads are done");
}

From source file:net.kmycode.javaspeechserver.cloud.StreamingRecognizeClient.java

/** Send streaming recognize requests to server. */
public void recognize() throws InterruptedException, IOException {
    final AudioRecorder recorder = AudioRecorder.getDefault();
    final StopWatch stopwatch = new StopWatch();

    final CountDownLatch finishLatch = new CountDownLatch(1);
    StreamObserver<StreamingRecognizeResponse> responseObserver = new StreamObserver<StreamingRecognizeResponse>() {
        private int sentenceLength = 1;

        /**/*w  w w  .  j  a  v a  2 s .  c om*/
        * Prints the transcription results. Interim results are overwritten by subsequent
        * results, until a final one is returned, at which point we start a new line.
        *
        * Flags the program to exit when it hears "exit".
        */
        @Override
        public void onNext(StreamingRecognizeResponse response) {

            byteStringQueue.clear();
            stopwatch.reset();

            List<StreamingRecognitionResult> results = response.getResultsList();
            if (results.size() < 1) {
                return;
            }

            StreamingRecognitionResult result = results.get(0);
            String transcript = result.getAlternatives(0).getTranscript();

            // Print interim results with a line feed, so subsequent transcriptions will overwrite
            // it. Final result will print a newline.
            String format = "%-" + this.sentenceLength + 's';
            format += " (" + result.getAlternatives(0).getConfidence() + ") ";
            if (result.getIsFinal()) {
                format += '\n';
                this.sentenceLength = 1;
                finishLatch.countDown();
            } else {
                format += '\r';
                this.sentenceLength = transcript.length();
            }
            System.out.print(String.format(format, transcript));
        }

        @Override
        public void onError(Throwable error) {
            logger.log(Level.ERROR, "recognize failed: {0}", error);
            finishLatch.countDown();
        }

        @Override
        public void onCompleted() {
            logger.info("recognize completed.");
            finishLatch.countDown();
        }
    };

    this.requestObserver = this.speechClient.streamingRecognize(responseObserver);
    try {
        // Build and send a StreamingRecognizeRequest containing the parameters for
        // processing the audio.
        RecognitionConfig config = RecognitionConfig.newBuilder()
                .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16).setSampleRate(recorder.getSamplingRate())
                .setLanguageCode("ja-JP").build();
        StreamingRecognitionConfig streamingConfig = StreamingRecognitionConfig.newBuilder().setConfig(config)
                .setInterimResults(true).setSingleUtterance(false).build();

        StreamingRecognizeRequest initial = StreamingRecognizeRequest.newBuilder()
                .setStreamingConfig(streamingConfig).build();
        requestObserver.onNext(initial);

        while (this.byteStringQueue.size() > 0) {
            ByteString data = this.byteStringQueue.poll();
            this.request(data);
        }

        // Read and send sequential buffers of audio as additional RecognizeRequests.
        while (finishLatch.getCount() > 0 && recorder.read()) {
            if (recorder.isSound()) {
                ByteString data = this.recorder.getBufferAsByteString();
                this.byteStringQueue.add(data);

                if (!stopwatch.isStarted()) {
                    stopwatch.start();
                } else if (stopwatch.getTime() > 2000) {
                    this.byteStringQueue.clear();
                    break;
                }

                this.request(data);
            } else {
                this.notSoundCount++;
                if (this.notSoundCount >= 3) {
                    // stop recognizition
                    break;
                }
            }
        }
    } catch (RuntimeException e) {
        // Cancel RPC.
        requestObserver.onError(e);
        throw e;
    }
    // Mark the end of requests.
    requestObserver.onCompleted();

    // Receiving happens asynchronously.
    finishLatch.await(1, TimeUnit.MINUTES);
}

From source file:org.elasticsearch.client.BulkProcessorIT.java

public void testBulkProcessorFlush() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    BulkProcessorTestListener listener = new BulkProcessorTestListener(latch);

    int numDocs = randomIntBetween(10, 100);

    try (BulkProcessor processor = initBulkProcessorBuilder(listener)
            //let's make sure that this bulk won't be automatically flushed
            .setConcurrentRequests(randomIntBetween(0, 10)).setBulkActions(numDocs + randomIntBetween(1, 100))
            .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB))
            .build()) {/*from   ww w  .j a va 2  s .  c o  m*/

        MultiGetRequest multiGetRequest = indexDocs(processor, numDocs);

        assertThat(latch.await(randomInt(500), TimeUnit.MILLISECONDS), equalTo(false));
        //we really need an explicit flush as none of the bulk thresholds was reached
        processor.flush();
        latch.await();

        assertThat(listener.beforeCounts.get(), equalTo(1));
        assertThat(listener.afterCounts.get(), equalTo(1));
        assertThat(listener.bulkFailures.size(), equalTo(0));
        assertResponseItems(listener.bulkItems, numDocs);
        assertMultiGetResponse(highLevelClient().multiGet(multiGetRequest), numDocs);
    }
}

From source file:com.networknt.graphql.security.JwtVerifyHandlerTest.java

@Test
public void testWithRightScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//  w  w  w . j  a v  a  2  s .c o m
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet/111").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiV0Z1VVZneE83dmxKUm5XUlllMjE1dyIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJmN2Q0MjM0OC1jNjQ3LTRlZmItYTUyZC00YzU3ODc0MjFlNzIiLCJzY29wZSI6WyJ3cml0ZTpwZXRzIiwicmVhZDpwZXRzIl19.ZDlD_JbtHMqfx8EWOlOXI0zFGjB_pJ6yXWpxoE03o2yQnCUq1zypaDTJWSiy-BPIiQAxwDV09L3SN7RsOcgJ3y2LLFhgqIXhcHoePxoz52LPOeeiihG2kcrgBm-_VMq0uUykLrD-ljSmmSm1Hai_dx0WiYGAEJf-TiD1mgzIUTlhogYrjFKlp2NaYHxr7yjzEGefKv4DWdjtlEMmX_cXkqPgxra_omzyxeWE-n0b7f_r7Hr5HkxnmZ23gkZcvFXfVWKEp2t0_dYmNCbSVDavAjNanvmWsNThYNglFRvF0lm8kl7jkfMO1pTa0WLcBLvOO2y_jRWjieFCrc0ksbIrXA");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(body);
    }
}

From source file:fi.jumi.launcher.remote.ProcessStartingDaemonSummonerTest.java

@Test
public void reports_an_internal_error_if_the_daemon_fails_to_connect_within_a_timeout()
        throws InterruptedException {
    SpyListener<SuiteListener> spy = new SpyListener<>(SuiteListener.class);
    SuiteListener expect = spy.getListener();
    CountDownLatch expectedMessagesArrived = new CountDownLatch(3);

    expect.onSuiteStarted();/*  ww w. ja v a2  s.  c  o m*/
    expect.onInternalError("Failed to start the test runner daemon process",
            StackTrace.from(new RuntimeException("Could not connect to the daemon: timed out after 0 ms")));
    expect.onSuiteFinished();
    spy.replay();

    daemonSummoner.connectToDaemon(dummySuiteConfig,
            new DaemonConfigurationBuilder().setStartupTimeout(0).freeze(),
            actorRef(new FakeDaemonListener(countMessages(expect, expectedMessagesArrived))));

    expectedMessagesArrived.await(TIMEOUT / 2, TimeUnit.MILLISECONDS);
    spy.verify();
}

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

@Test
public void testDeleteDhcpRelayProfile() throws IOException, InterruptedException {
    setupMocks(null, HttpStatus.SC_OK);// w ww .  ja v a  2 s  . c o m

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.deleteDhcpRelayProfile("id", new com.google.common.util.concurrent.FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            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.supermy.im.mongo.MongoRepository.java

/**
 *
 * @param collectionName/*ww  w . j a  v a2s .  c o m*/
 * @return
 */
public boolean collectionExists(final String collectionName) {

    MongoIterable colls = mongoDatabase().listCollectionNames();

    List<String> collectionNames = new ArrayList<String>();

    try {
        final CountDownLatch countDownLatch = new CountDownLatch(1);//??

        colls.into(collectionNames, new SingleResultCallback<Void>() {
            @Override
            public void onResult(final Void result, final Throwable t) {
                // logger.debug("?");
                countDownLatch.countDown();
            }
        });
        countDownLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(collectionNames);
    System.out.println(collectionNames.size());

    for (String name : collectionNames) {
        if (name.equalsIgnoreCase(collectionName)) {
            return true;
        }
    }
    return false;
}

From source file:com.greplin.zookeeper.RobustZooKeeper.java

public void sync() throws IOException, InterruptedException {

    log.info("Called sync() on client " + clientNumber);
    final CountDownLatch waitForSync = new CountDownLatch(1);
    final ZooKeeper c = getClient();
    assert c.getState().isAlive();

    c.sync("/", new AsyncCallback.VoidCallback() {
        @Override//from w ww  .j a  v  a2  s . c o m
        public void processResult(int rc, String path, Object ctx) {
            log.info("Sync callback triggered on client " + clientNumber);
            waitForSync.countDown();
        }
    }, null);

    log.info("Waitng for sync callback on client " + clientNumber);
    waitForSync.await();

    log.info("sync() finished on " + clientNumber);
    return;
}