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:io.undertow.server.handlers.RequestLimitingHandlerTestCase.java

@Test
public void testRateLimitingHandler() throws ExecutionException, InterruptedException {
    latch.countDown();//from  www.  jav  a 2  s  .  c o  m
    latch = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
    try {
        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < N_THREADS; ++i) {
            futures.add(executor.submit(new Callable<String>() {
                @Override
                public String call() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                        HttpResponse result = client.execute(get);
                        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                        return HttpClientUtils.readResponse(result);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        Thread.sleep(300);
        latch.countDown();
        for (Future<?> future : futures) {
            String res = (String) future.get();
            Assert.assertTrue(res, res.equals("1") || res.equals("2"));
        }
    } finally {
        executor.shutdown();
    }

}

From source file:com.github.jguaneri.notifications.web.controller.NotificationController.java

/**
 * @since 1.0// w  ww.  ja v  a 2  s .c  o m
 * @param channel
 * @param resource
 */
@RequestMapping(value = "/subscribe/{channel}", method = RequestMethod.GET)
@ResponseBody
public void subscribe(@PathVariable("channel") final String channel, final AtmosphereResource resource,
        Principal principal) throws Exception {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    resource.addEventListener(new AtmosphereResourceEventListenerAdapter() {
        @Override
        public void onSuspend(AtmosphereResourceEvent event) {
            countDownLatch.countDown();
            LOGGER.info("Suspending Client..." + resource.uuid());
            resource.removeEventListener(this);
        }

        @Override
        public void onDisconnect(AtmosphereResourceEvent event) {
            LOGGER.info("Disconnecting Client..." + resource.uuid());
            super.onDisconnect(event);
        }

        @Override
        public void onBroadcast(AtmosphereResourceEvent event) {
            LOGGER.info("Client is broadcasting..." + resource.uuid());
            super.onBroadcast(event);
        }

    });

    if (AtmosphereResource.TRANSPORT.LONG_POLLING.equals(resource.transport())) {
        resource.resumeOnBroadcast(true).suspend(-1);
    } else {
        resource.suspend(-1);
    }

    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted while trying to suspend resource {}", resource);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Subscribing to channel: {}", channel);
    }
    final Client client = new Client();
    client.setSubscriptionId(resource.uuid());
    channelService.subscribe(client, channel);
}

From source file:com.imagesleuth.imagesleuthclient2.Poster.java

public String Post(final File imgFile) throws IOException, ImageReadException, InterruptedException {

    final ArrayList<String> idArray = new ArrayList<>();

    final CountDownLatch latch = new CountDownLatch(1);

    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultHeaders(harray)
            .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig).build()) {
        httpclient.start();//from   ww w  . j a va  2s .c  o m
        final byte[] imageAsBytes = IOUtils.toByteArray(new FileInputStream(imgFile));
        final ImageInfo info = Imaging.getImageInfo(imageAsBytes);
        final HttpPost request = new HttpPost(urlval);
        String boundary = UUID.randomUUID().toString();
        HttpEntity mpEntity = MultipartEntityBuilder.create().setBoundary("-------------" + boundary)
                .addBinaryBody("file", imageAsBytes, ContentType.create(info.getMimeType()), imgFile.getName())
                .build();
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        mpEntity.writeTo(baoStream);
        request.setHeader("Content-Type", "multipart/form-data;boundary=-------------" + boundary);
        //equest.setHeader("Content-Type", "multipart/form-data");                               
        NByteArrayEntity entity = new NByteArrayEntity(baoStream.toByteArray(),
                ContentType.MULTIPART_FORM_DATA);
        request.setEntity(entity);
        httpclient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {
                int code = response.getStatusLine().getStatusCode();
                //System.out.println(" response code: " + code + " for image: " + imgFile.getName());
                if (response.getEntity() != null && code == 202) {
                    StringWriter writer = new StringWriter();
                    try {
                        IOUtils.copy(response.getEntity().getContent(), writer);
                        idArray.add(writer.toString());
                        writer.close();
                        //System.out.println(" response id: " + id + " for image "+ img.getName()); 
                        latch.countDown();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    System.out.println(" response code: " + code + " for image: " + imgFile.getName()
                            + " reason " + response.getStatusLine().getReasonPhrase());
                }
            }

            @Override
            public void failed(final Exception ex) {
                System.out.println(request.getRequestLine() + imgFile.getName() + "->" + ex);
                latch.countDown();
            }

            @Override
            public void cancelled() {
                System.out.println(request.getRequestLine() + " cancelled");
                latch.countDown();
            }

        });
        latch.await();
    }
    if (idArray.isEmpty()) {
        return null;
    } else {
        return idArray.get(0);
    }
}

From source file:DFSBenchmark.java

public DFSBenchmark(int threads, Path basePath) {
    this.threads = threads;
    this.baseDirPath = basePath;
    greenSignal = new CountDownLatch(threads);
    service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threads));
    reporter.enable(metrics, 3000, TimeUnit.MILLISECONDS);
}

From source file:hws.util.ZkDataMonitor.java

public ZkClient(String serverAddr, int sessionTimeout) throws IOException, InterruptedException {
    final CountDownLatch connectedSignal = new CountDownLatch(1);
    this.zk = new ZooKeeper(serverAddr, sessionTimeout, new Watcher() {
        @Override// w w  w .  ja va  2 s  . co m
        public void process(WatchedEvent event) {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                connectedSignal.countDown();
            }
        }
    });
    connectedSignal.await();
}

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

@Test
public void testCreateAsync() throws Exception {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

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

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override//  w  w w  .  ja va2  s  .  c  o  m
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            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.watchrabbit.executor.spring.AnnotationDiscoverTest.java

@Test
public void shouldCloseCircuit() throws Exception {
    try {//w  w w.  j  a  v a2  s .  c  o  m
        annotatedService.fastClose(() -> {
            throw new Exception();
        });
        failBecauseExceptionWasNotThrown(Exception.class);
    } catch (Exception ex) {
    }
    Sleep.untilTrue(Boolean.TRUE::booleanValue, 10, TimeUnit.MILLISECONDS);

    CountDownLatch latch = new CountDownLatch(1);
    annotatedService.fastClose(() -> {
        latch.countDown();
        return "ok";
    });
    assertThat(latch.getCount()).isEqualTo(0);
}

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

@Test
public void testCreateAsync() throws Exception {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

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

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    FlavorApi flavorApi = new FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override//from ww  w  .j  a  va  2s  .c  om
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            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.linkedin.pinot.core.query.scheduler.PrioritySchedulerTest.java

@AfterMethod
public void afterMethod() {
    useBarrier = false;
    startupBarrier = null;
    validationBarrier = null;
    numQueries = new CountDownLatch(1);
}

From source file:com.canoo.dolphin.client.impl.TestDolphinPlatformHttpClientConnector.java

@Test(expectedExceptions = DolphinRemotingException.class)
public void testBadResponse() {
    final CountDownLatch httpWasCalled = new CountDownLatch(1);

    HttpClient httpClient = new DefaultHttpClient() {

        @Override/*from   w  ww .  j av a 2s. com*/
        public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
                throws IOException, ClientProtocolException {
            StatusLine statusLine = new StatusLine() {
                @Override
                public ProtocolVersion getProtocolVersion() {
                    return new ProtocolVersion("Dummy-Protocol", 1, 1);
                }

                @Override
                public int getStatusCode() {
                    return 500;
                }

                @Override
                public String getReasonPhrase() {
                    return "Internal Server Error";
                }
            };
            StringEntity entity = new StringEntity("failed");
            HttpResponse response = new BasicHttpResponse(statusLine);
            response.setEntity(entity);
            responseHandler.handleResponse(response);
            httpWasCalled.countDown();
            return (T) "[]";
        }
    };
    DolphinPlatformHttpClientConnector connector = new DolphinPlatformHttpClientConnector(new ClientDolphin(),
            new JsonCodec(), httpClient, getDummyURL(), new ForwardableCallback<>(),
            new DummyUiThreadHandler());

    connector.transmit(Collections.singletonList(new Command()));
}