List of usage examples for java.util.concurrent CountDownLatch CountDownLatch
public CountDownLatch(int count)
From source file:com.frostwire.search.tests.KATSearchTest.java
public static void main(String[] args) throws InterruptedException { SearchEngine KAT = new SearchEngine(1, "KAT", SearchEnginesSettings.KAT_SEARCH_ENABLED, "kat.cr") { @Override// w w w . j ava2s .c om public SearchPerformer getPerformer(long token, String keywords) { return new KATSearchPerformer(KAT.getDomainName(), token, keywords, 10000); } }; final CountDownLatch latch = new CountDownLatch(1); final SearchPerformer performer; performer = KAT.getPerformer(1, "public domain"); Action1 onNextAction = new Action1<List<? extends SearchResult>>() { @Override public void call(List<? extends SearchResult> searchResults) { System.out.println("doOnNext!"); if (searchResults instanceof List) { try { if (!testOnSearchResults((List<KATSearchResult>) searchResults)) { System.out.println("Test failed."); } else { System.out.println("Test passed."); } } catch (IOException e) { e.printStackTrace(); } latch.countDown(); } } }; final Observable<List<? extends SearchResult>> observable = performer.observable(); observable.forEach(onNextAction); performer.perform(); System.out.println("performer.perform()\nWaiting..."); latch.await(); //System.out.println("Bye bye"); /** byte[] readAllBytes = Files.readAllBytes(Paths.get("/Users/gubatron/tmp/eztv4.html")); String fileStr = new String(readAllBytes,"utf-8"); //Pattern pattern = Pattern.compile(REGEX); Pattern pattern = Pattern.compile(HTML_REGEX); Matcher matcher = pattern.matcher(fileStr); int found = 0; while (matcher.find()) { found++; System.out.println("\nfound " + found); System.out.println("displayname: " + matcher.group("displayname")); System.out.println("infohash: " + matcher.group("infohash")); System.out.println("torrenturl: " + matcher.group("torrenturl")); System.out.println("creationtime: " + matcher.group("creationtime")); System.out.println("filesize: " + matcher.group("filesize")); System.out.println("==="); } //System.out.println("-done-"); */ }
From source file:ch.rasc.wampspring.demo.client.CallClientSockJs.java
public static void main(String[] args) throws InterruptedException { List<Transport> transports = new ArrayList<>(2); transports.add(new WebSocketTransport(new StandardWebSocketClient())); transports.add(new RestTemplateXhrTransport()); WebSocketClient webSocketClient = new SockJsClient(transports); JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper()); CountDownLatch latch = new CountDownLatch(10_000); TestTextWebSocketHandler handler = new TestTextWebSocketHandler(jsonFactory, latch); Long[] start = new Long[1]; ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler, "ws://localhost:8080/wampOverSockJS"); future.addCallback(wss -> {// w w w . jav a 2 s . c o m start[0] = System.currentTimeMillis(); for (int i = 0; i < 10_000; i++) { CallMessage callMessage = new CallMessage(UUID.randomUUID().toString(), "testService.sum", i, i + 1); try { wss.sendMessage(new TextMessage(callMessage.toJson(jsonFactory))); } catch (Exception e) { System.out.println("ERROR SENDING CALLMESSAGE" + e); latch.countDown(); } } }, t -> { System.out.println("DO HANDSHAKE ERROR: " + t); System.exit(1); }); if (!latch.await(3, TimeUnit.MINUTES)) { System.out.println("SOMETHING WENT WRONG"); } System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds"); System.out.println("SUCCESS: " + handler.getSuccess()); System.out.println("ERROR : " + handler.getError()); }
From source file:com.weibo.motan.demo.client.DemoRpcClient.java
public static void main(String[] args) throws Exception { final DescriptiveStatistics stats = new SynchronizedDescriptiveStatistics(); int threads = Integer.parseInt(args[0]); DubboBenchmark.BenchmarkMessage msg = prepareArgs(); final byte[] msgBytes = msg.toByteArray(); int n = 1000000; final CountDownLatch latch = new CountDownLatch(n); ExecutorService es = Executors.newFixedThreadPool(threads); final AtomicInteger trans = new AtomicInteger(0); final AtomicInteger transOK = new AtomicInteger(0); ApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] { "classpath:motan_demo_client.xml" }); MotanDemoService service = (MotanDemoService) ctx.getBean("motanDemoReferer"); long start = System.currentTimeMillis(); for (int i = 0; i < n; i++) { es.submit(() -> {/*from w ww .j a va 2 s . c om*/ try { long t = System.currentTimeMillis(); DubboBenchmark.BenchmarkMessage m = testSay(service, msgBytes); t = System.currentTimeMillis() - t; stats.addValue(t); trans.incrementAndGet(); if (m != null && m.getField1().equals("OK")) { transOK.incrementAndGet(); } } finally { latch.countDown(); } }); } latch.await(); start = System.currentTimeMillis() - start; System.out.printf("sent requests : %d\n", n); System.out.printf("received requests : %d\n", trans.get()); System.out.printf("received requests_OK : %d\n", transOK.get()); System.out.printf("throughput (TPS) : %d\n", n * 1000 / start); System.out.printf("mean: %f\n", stats.getMean()); System.out.printf("median: %f\n", stats.getPercentile(50)); System.out.printf("max: %f\n", stats.getMax()); System.out.printf("min: %f\n", stats.getMin()); System.out.printf("99P: %f\n", stats.getPercentile(90)); }
From source file:com.example.AsyncClientHttpExchangeFutureCallback.java
public static void main(String[] args) throws Exception { HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); httpclient.start();// w w w . j a v a 2 s .com try { HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.shutdown(); } System.out.println("Done"); }
From source file:com.boonya.http.async.examples.nio.client.AsyncClientHttpExchangeFutureCallback.java
public static void main(final String[] args) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig) .build();/*from www . j a va 2 s.co m*/ try { httpclient.start(); final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:rg.apache.http.examples.async.AsyncClientHttpExchangeFutureCallback.java
public static void main(final String[] args) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig) .setThreadFactory(new NamedThreadFactory("dddddddd")).build(); try {//from w w w . ja va 2s . c om httpclient.start(); final HttpGet[] requests = new HttpGet[] { new HttpGet("http://httpbin.org/ip"), new HttpGet("https://httpbin.org/ip"), new HttpGet("http://httpbin.org/headers") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:io.pivotal.ListApplicationsApplication.java
public static void main(String[] args) throws InterruptedException { ConfigurableApplicationContext applicationContext = SpringApplication.run(ListApplicationsApplication.class, args);//from w w w . j av a 2 s .c o m CloudFoundryClient cloudFoundryClient = applicationContext.getBean(CloudFoundryClient.class); CloudFoundryOperations cloudFoundryOperations = applicationContext.getBean(CloudFoundryOperations.class); CountDownLatch latch = new CountDownLatch(1); cloudFoundryOperations.applications().list().flatMap( application -> Mono.just(application).and(getServiceInstances(cloudFoundryClient, application))) .map(function(FormattingUtils::formatApplication)).subscribe(System.out::println, t -> { t.printStackTrace(); latch.countDown(); }, latch::countDown); latch.await(); }
From source file:com.twitter.distributedlog.basic.MultiReader.java
public static void main(String[] args) throws Exception { if (2 != args.length) { System.out.println(HELP); return;//from w w w.j av a 2 s . co m } String dlUriStr = args[0]; final String streamList = args[1]; URI uri = URI.create(dlUriStr); DistributedLogConfiguration conf = new DistributedLogConfiguration(); DistributedLogNamespace namespace = DistributedLogNamespaceBuilder.newBuilder().conf(conf).uri(uri).build(); String[] streamNameList = StringUtils.split(streamList, ','); DistributedLogManager[] managers = new DistributedLogManager[streamNameList.length]; for (int i = 0; i < managers.length; i++) { String streamName = streamNameList[i]; // open the dlm System.out.println("Opening log stream " + streamName); managers[i] = namespace.openLog(streamName); } final CountDownLatch keepAliveLatch = new CountDownLatch(1); for (DistributedLogManager dlm : managers) { final DistributedLogManager manager = dlm; dlm.getLastLogRecordAsync().addEventListener(new FutureEventListener<LogRecordWithDLSN>() { @Override public void onFailure(Throwable cause) { if (cause instanceof LogNotFoundException) { System.err.println( "Log stream " + manager.getStreamName() + " is not found. Please create it first."); keepAliveLatch.countDown(); } else if (cause instanceof LogEmptyException) { System.err.println("Log stream " + manager.getStreamName() + " is empty."); readLoop(manager, DLSN.InitialDLSN, keepAliveLatch); } else { System.err.println("Encountered exception on process stream " + manager.getStreamName()); keepAliveLatch.countDown(); } } @Override public void onSuccess(LogRecordWithDLSN record) { readLoop(manager, record.getDlsn(), keepAliveLatch); } }); } keepAliveLatch.await(); for (DistributedLogManager dlm : managers) { dlm.close(); } namespace.close(); }
From source file:httpasync.QuickStart.java
public static void main(String[] args) throws Exception { CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try {/*from w w w . j a va 2 s .c o m*/ // Start the client httpclient.start(); // Execute request final HttpGet request1 = new HttpGet("http://www.apache.org/"); Future<HttpResponse> future = httpclient.execute(request1, null); // and wait until response is received HttpResponse response1 = future.get(); System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine()); // One most likely would want to use a callback for operation result final CountDownLatch latch1 = new CountDownLatch(1); final HttpGet request2 = new HttpGet("http://www.apache.org/"); httpclient.execute(request2, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response2) { latch1.countDown(); System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine()); } @Override public void failed(final Exception ex) { latch1.countDown(); System.out.println(request2.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch1.countDown(); System.out.println(request2.getRequestLine() + " cancelled"); } }); latch1.await(); // In real world one most likely would want also want to stream // request and response body content final CountDownLatch latch2 = new CountDownLatch(1); final HttpGet request3 = new HttpGet("http://www.apache.org/"); HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3); AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() { HttpResponse response; @Override protected void onResponseReceived(final HttpResponse response) { this.response = response; } @Override protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException { // Do something useful } @Override protected void releaseResources() { } @Override protected HttpResponse buildResult(final HttpContext context) { return this.response; } }; httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response3) { latch2.countDown(); System.out.println(request2.getRequestLine() + "->" + response3.getStatusLine()); } @Override public void failed(final Exception ex) { latch2.countDown(); System.out.println(request2.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch2.countDown(); System.out.println(request2.getRequestLine() + " cancelled"); } }); latch2.await(); } finally { httpclient.close(); } }
From source file:com.boonya.http.async.examples.nio.client.AsyncClientEvictExpiredConnections.java
public static void main(String[] args) throws Exception { ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor); cm.setMaxTotal(100);/* www . j a va 2s.c o m*/ CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(cm).build(); try { httpclient.start(); // create an array of URIs to perform GETs on String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/", }; IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); connEvictor.start(); final CountDownLatch latch = new CountDownLatch(urisToGet.length); for (final String uri : urisToGet) { final HttpGet httpget = new HttpGet(uri); httpclient.execute(httpget, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(httpget.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(httpget.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(httpget.getRequestLine() + " cancelled"); } }); } latch.await(); // Sleep 10 sec and let the connection evictor do its job Thread.sleep(20000); // Shut down the evictor thread connEvictor.shutdown(); connEvictor.join(); } finally { httpclient.close(); } }