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:org.sglover.nlp.CoreNLPEntityTagger.java

@PostConstruct
public void init() throws InterruptedException {
    String namesModelFilePath = "models/en-ner-person.bin";
    String datesModelFilePath = "models/en-ner-date.bin";
    String locationsModelFilePath = "models/en-ner-location.bin";
    String orgsModelFilePath = "models/en-ner-organization.bin";
    String moneyModelFilePath = "models/en-ner-money.bin";
    String tokenModelPath = "models/en-token.bin";
    String posModelPath = "models/en-pos-maxent.bin";
    String sentenceModelPath = "models/en-sent.bin";
    String chunkerModelPath = "models/en-chunker.bin";

    CountDownLatch countDownLatch = new CountDownLatch(9);

    new Thread(new SentenceModelLoader(sentenceModelPath, "en", countDownLatch)).start();

    new Thread(new ChunkerModelLoader(chunkerModelPath, "en", countDownLatch)).start();

    new Thread(new TokenizerModelLoader(tokenModelPath, "en", countDownLatch)).start();

    new Thread(new POSModelLoader(posModelPath, "en", countDownLatch)).start();

    new Thread(new TokenNameFinderLoader(moneyModelFilePath, "money", countDownLatch, tokenNameFinders))
            .start();// ww w. ja  va  2 s.c  om
    new Thread(new TokenNameFinderLoader(namesModelFilePath, "name", countDownLatch, tokenNameFinders)).start();
    new Thread(new TokenNameFinderLoader(datesModelFilePath, "date", countDownLatch, tokenNameFinders)).start();
    new Thread(new TokenNameFinderLoader(locationsModelFilePath, "location", countDownLatch, tokenNameFinders))
            .start();
    new Thread(new TokenNameFinderLoader(orgsModelFilePath, "orgs", countDownLatch, tokenNameFinders)).start();

    countDownLatch.await(15, TimeUnit.SECONDS);
}

From source file:de.jackwhite20.japs.shared.nio.NioSocketClient.java

public boolean connect(String host, int port) {

    ChannelFuture channelFuture = new Bootstrap().group(PipelineUtils.newEventLoopGroup(1))
            .channel(PipelineUtils.getChannel()).handler(new ClientChannelInitializer(this))
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT).connect(host, port);

    channelFuture.awaitUninterruptibly();

    channel = channelFuture.channel();/*from  w w  w.  ja  v  a2  s.  c  o  m*/

    CountDownLatch countDownLatch = new CountDownLatch(1);

    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            connected = channelFuture.isSuccess();

            countDownLatch.countDown();
        }
    });

    try {
        countDownLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return connected;
}

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

public void testDelete() {
    prepareFolder();//from   www  . j a  va2 s  .c  o  m
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                deleteAndCheck();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testDelete() timed out");
        }
    } catch (InterruptedException e) {
        fail("testDelete() has been interrupted");
    }
}

From source file:com.uber.hoodie.common.util.queue.BoundedInMemoryExecutor.java

/**
 * Start all Producers//from   w w w.  j  a  v a  2s .  c  om
 */
public ExecutorCompletionService<Boolean> startProducers() {
    // Latch to control when and which producer thread will close the queue
    final CountDownLatch latch = new CountDownLatch(producers.size());
    final ExecutorCompletionService<Boolean> completionService = new ExecutorCompletionService<Boolean>(
            executorService);
    producers.stream().map(producer -> {
        return completionService.submit(() -> {
            try {
                preExecute();
                producer.produce(queue);
            } catch (Exception e) {
                logger.error("error consuming records", e);
                queue.markAsFailed(e);
                throw e;
            } finally {
                synchronized (latch) {
                    latch.countDown();
                    if (latch.getCount() == 0) {
                        // Mark production as done so that consumer will be able to exit
                        queue.close();
                    }
                }
            }
            return true;
        });
    }).collect(Collectors.toList());
    return completionService;
}

From source file:com.examples.cloud.speech.StreamingRecognizeClient.java

/** Send streaming recognize requests to server. */
public void recognize() throws InterruptedException, IOException {
    final CountDownLatch finishLatch = new CountDownLatch(1);
    StreamObserver<StreamingRecognizeResponse> responseObserver = new StreamObserver<StreamingRecognizeResponse>() {
        @Override/* w w  w. j a v a2s .c o m*/
        public void onNext(StreamingRecognizeResponse response) {
            logger.info("Received response: " + TextFormat.printToString(response));
        }

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

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

    StreamObserver<StreamingRecognizeRequest> requestObserver = speechClient
            .streamingRecognize(responseObserver);
    try {
        // Build and send a StreamingRecognizeRequest containing the parameters for
        // processing the audio.
        RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.LINEAR16)
                .setSampleRate(samplingRate).build();
        StreamingRecognitionConfig streamingConfig = StreamingRecognitionConfig.newBuilder().setConfig(config)
                .setInterimResults(true).setSingleUtterance(true).build();

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

        // Open audio file. Read and send sequential buffers of audio as additional RecognizeRequests.
        FileInputStream in = new FileInputStream(new File(file));
        // For LINEAR16 at 16000 Hz sample rate, 3200 bytes corresponds to 100 milliseconds of audio.
        byte[] buffer = new byte[BYTES_PER_BUFFER];
        int bytesRead;
        int totalBytes = 0;
        int samplesPerBuffer = BYTES_PER_BUFFER / BYTES_PER_SAMPLE;
        int samplesPerMillis = samplingRate / 1000;

        while ((bytesRead = in.read(buffer)) != -1) {
            totalBytes += bytesRead;
            StreamingRecognizeRequest request = StreamingRecognizeRequest.newBuilder()
                    .setAudioContent(ByteString.copyFrom(buffer, 0, bytesRead)).build();
            requestObserver.onNext(request);
            // To simulate real-time audio, sleep after sending each audio buffer.
            Thread.sleep(samplesPerBuffer / samplesPerMillis);
        }
        logger.info("Sent " + totalBytes + " bytes from audio file: " + file);
    } 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:com.microsoft.office.core.EventsAsyncTestCase.java

@Test(timeout = 60000)
public void updateTest() throws Exception {
    prepareEvent();//  w  ww.  j  a v a2  s. co  m
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                updateAndCheck();
                removeEvent();
            } catch (Throwable t) {
                reportError(t);
            }

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

From source file:org.callimachusproject.script.ConcurrentResponseTest.java

public void testResponseConcurrent() throws Throwable {
    int n = Runtime.getRuntime().availableProcessors() * 4;
    final CountDownLatch up = new CountDownLatch(1);
    final CountDownLatch down = new CountDownLatch(n);
    final List<Throwable> errors = new ArrayList<Throwable>(n);
    for (int i = 0; i < n; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    up.await();//from  ww  w .ja  v a 2s  .com
                    for (int i = 0; i < 100; i++) {
                        testJsonResponse();
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                    synchronized (errors) {
                        errors.add(e);
                    }
                } finally {
                    down.countDown();
                }
            }
        }).start();
    }
    up.countDown();
    down.await();
    synchronized (errors) {
        if (!errors.isEmpty()) {
            throw errors.get(0);
        }
    }
}

From source file:com.vmware.photon.controller.api.client.resource.ProjectApiTest.java

@Test
public void testGetProjectAsync() throws IOException, InterruptedException {
    final Project project1 = new Project();
    project1.setId("project1");

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(project1);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ProjectApi projectApi = new ProjectApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    projectApi.getProjectAsync("foo", new FutureCallback<Project>() {
        @Override/*from w  w  w  .j  ava 2s.c  o  m*/
        public void onSuccess(@Nullable Project result) {
            assertEquals(result, project1);
            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:io.liveoak.container.BasicServerTest.java

@Test
public void testServer() throws Exception {

    CompletableFuture<StompMessage> peopleCreationNotification = new CompletableFuture<>();
    CompletableFuture<StompMessage> bobCreationNotification = new CompletableFuture<>();

    StompClient stompClient = new StompClient();

    CountDownLatch subscriptionLatch = new CountDownLatch(1);

    stompClient.connect("localhost", 8080, (client) -> {
        stompClient.subscribe("/testApp/memory/people/*", (subscription) -> {
            subscription.onMessage((msg) -> {
                System.err.println("******* MESSAGE: " + msg);
                if (msg.headers().get("location").equals("/testApp/memory/people")) {
                    peopleCreationNotification.complete(msg);
                } else {
                    bobCreationNotification.complete(msg);
                }//from   w w w  .  j a  v a2  s  . c  om
            });
            subscription.onReceipt(() -> {
                subscriptionLatch.countDown();
            });
        });
    });

    subscriptionLatch.await();

    Header header = new BasicHeader("Accept", "application/json");

    HttpGet getRequest = null;
    HttpPost postRequest = null;
    HttpPut putRequest = null;
    CloseableHttpResponse response = null;

    System.err.println("TEST #1");
    // Root object should exist.
    getRequest = new HttpGet("http://localhost:8080/testApp/memory");
    getRequest.addHeader(header);

    response = this.httpClient.execute(getRequest);

    //  {
    //    "id" : "memory",
    //    "self" : {
    //      "href" : "/memory"
    //    },
    //   "content" : [ ]
    // }

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    ResourceState state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state.members().size()).isEqualTo(0);

    response.close();

    System.err.println("TEST #2");
    // people collection should not exist.

    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people");

    response = this.httpClient.execute(getRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(404);

    response.close();

    System.err.println("TEST #3");
    // create people collection with direct PUT

    putRequest = new HttpPut("http://localhost:8080/testApp/memory/people");
    putRequest.setEntity(new StringEntity("{ \"type\": \"collection\" }"));
    putRequest.setHeader("Content-Type", "application/json");
    response = this.httpClient.execute(putRequest);
    System.err.println("response: " + response);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    response.close();

    System.err.println("TEST #4");
    // people collection should exist now.

    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people");

    response = this.httpClient.execute(getRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    response.close();

    assertThat(peopleCreationNotification.getNow(null)).isNull();

    System.err.println("TEST #5");
    // people collection should be enumerable from the root

    getRequest = new HttpGet("http://localhost:8080/testApp/memory?expand=members");
    getRequest.addHeader(header);

    response = this.httpClient.execute(getRequest);

    //        {
    //          "id" : "memory",
    //          "self" : {
    //            "href" : "/memory"
    //          },
    //          "content" : [ {
    //            "id" : "people",
    //            "self" : {
    //                "href" : "/memory/people"
    //            },
    //            "content" : [ ]
    //          } ]
    //        }

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state.members().size()).isEqualTo(1);

    ResourceState memoryCollection = state.members().get(0);
    assertThat(memoryCollection.id()).isEqualTo("people");

    assertThat(memoryCollection.uri().toString()).isEqualTo("/testApp/memory/people");

    System.err.println("TEST #6");
    // Post a person

    postRequest = new HttpPost("http://localhost:8080/testApp/memory/people");
    postRequest.setEntity(new StringEntity("{ \"name\": \"bob\" }"));
    postRequest.setHeader("Content-Type", "application/json");

    response = httpClient.execute(postRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state).isInstanceOf(ResourceState.class);

    assertThat(state.id()).isNotNull();
    assertThat(state.getProperty("name")).isEqualTo("bob");

    // check STOMP
    System.err.println("TEST #STOMP");
    StompMessage obj = bobCreationNotification.get(30000, TimeUnit.SECONDS);
    assertThat(obj).isNotNull();

    ResourceState bobObjState = decode(obj.content());
    assertThat(bobObjState.getProperty("name")).isEqualTo("bob");

    assertThat(state.getProperty(LiveOak.ID)).isEqualTo(bobObjState.getProperty(LiveOak.ID));
    response.close();
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToPlainPipelineOutputs() throws InterruptedException, JSONException {
    firstStep = newPipelineWithResponseBody("{id:123}");

    // use a synchronized set to collect the pipeline output from multiple threads
    Set<JsonPipelineOutput> distinctOutputs = Collections.synchronizedSet(new HashSet<JsonPipelineOutput>());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    ExecutorService executorService = Executors.newCachedThreadPool();
    CountDownLatch countDown = new CountDownLatch(100);
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();/*w w w .j av a 2  s. com*/
            distinctOutputs.add(firstStep.getOutput().toBlocking().single());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    // ensure all threads received the same JsonPipelineOutput instance with the expected JSON output
    assertEquals(1, distinctOutputs.size());
    JSONAssert.assertEquals("{id: 123}", firstStep.getStringOutput().toBlocking().first(),
            JSONCompareMode.STRICT);
}