List of usage examples for java.util.concurrent CountDownLatch await
public void await() throws InterruptedException
From source file:com.griddynamics.jagger.JaggerLauncher.java
private static void launchKernel(final URL directory) { LaunchTask runKernel = new LaunchTask() { private Kernel kernel; @Override/*from ww w. ja v a 2 s.c o m*/ public void run() { log.info("Starting Kernel"); ApplicationContext context = loadContext(directory, KERNEL_CONFIGURATION, environmentProperties); final CountDownLatch latch = new CountDownLatch(1); final Coordinator coordinator = (Coordinator) context.getBean("coordinator"); kernel = (Kernel) context.getBean("kernel"); toTerminate(kernel); Runnable kernelRunner = new Runnable() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } kernel.run(); } }; getExecutor().execute(kernelRunner); coordinator.waitForReady(); coordinator.waitForInitialization(); latch.countDown(); } }; builder.addBackgroundTask(runKernel); }
From source file:cp.server.app.ClientMultiThreadedExecution.java
public static void fetch() throws Exception { // Create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. // PoolingHttpClientConnectionManager cm = new // PoolingHttpClientConnectionManager(); // cm.setMaxTotal(100); // CloseableHttpClient httpclient = HttpClients.custom() // .setConnectionManager(cm).build(); ExecutorService pool = Executors.newFixedThreadPool(10); ServerDAO dao = new ServerDAO(); List<Page> pages = null; Time ts = new Time(System.currentTimeMillis()); int interval; try {//w w w.j a v a 2 s .co m // // before 10am, query with the comment yesterday // if (Integer.valueOf(ts.toString().substring(0, 2)) > 10) // { // interval = 1; // } // else // { // interval = 2; // } // // pages = dao.queryPagesByDayInterval( // ConnectionFactory.getConnection(), interval); // // System.out.println("load comments from " + pages.size() + // "pages."); // for (Page page : pages) // { // PAGESTACK.push(page.getUrl()); // } } catch (Exception ex) { ex.printStackTrace(); } try { // create an array of URIs to perform GETs on String[] urisToGet = { "http://sports.sina.com.cn", "http://news.sina.com.cn", "http://ent.sina.com.cn", "http://tech.sina.com.cn", "http://sports.sina.com.cn/o/2013-10-27/04016852444.shtml", "http://finance.sina.com.cn/china/20131027/043917125695.shtml", "http://sports.sina.com.cn/j/2013-10-27/06336852561.shtml", "http://sports.sina.com.cn/j/2013-10-26/21006851844.shtml" }; for (int i = 0; i < 10000; i++) { for (int j = 0; j < urisToGet.length; j++) { PAGESTACK.push(urisToGet[j]); } } CountDownLatch cdl = new CountDownLatch(6); // create a thread for each URI GetThread[] threads = new GetThread[urisToGet.length]; for (int i = 0; i < 4; i++) { // HttpGet httpget = new HttpGet(urisToGet[i]); threads[i] = new GetThread(urisToGet[i], i + 1, cdl); } // start the threads for (int j = 0; j < 4; j++) { pool.execute(threads[j]); // threads[j].start(); } cdl.await(); } finally { // httpclient.close(); pool.shutdown(); } }
From source file:org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ArduinoServiceUtils.java
public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, boolean fireAndForgot) throws DeviceManagementException { String responseMsg = ""; String urlString = ArduinoConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; if (log.isDebugEnabled()) { log.debug(urlString);/*from w w w .j ava 2 s . c o m*/ } if (!fireAndForgot) { HttpURLConnection httpConnection = getHttpConnection(urlString); try { httpConnection.setRequestMethod(HttpMethod.GET); } catch (ProtocolException e) { String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:" + urlString; log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } responseMsg = readResponseFromGetRequest(httpConnection); } else { CloseableHttpAsyncClient httpclient = null; try { httpclient = HttpAsyncClients.createDefault(); httpclient.start(); HttpGet request = new HttpGet(urlString); final CountDownLatch latch = new CountDownLatch(1); Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { latch.countDown(); } @Override public void failed(Exception e) { latch.countDown(); } @Override public void cancelled() { latch.countDown(); } }); latch.await(); } catch (InterruptedException e) { if (log.isDebugEnabled()) { log.debug("Sync Interrupted"); } } finally { try { if (httpclient != null) { httpclient.close(); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed on close"); } } } } return responseMsg; }
From source file:com.test.database.jedis.TestJedisEvalLua.java
public static void generateTestData() throws InterruptedException { Jedis jedis = new Jedis(host, port); jedis.flushAll();//from w w w. ja v a2 s . c o m jedis.close(); final CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; ++i) { final int temp = i; Thread thread = new Thread() { public void run() { Jedis jedis = new Jedis(host, port); int per = honBaoCount / threadCount; JSONObject object = new JSONObject(); for (int j = temp * per; j < (temp + 1) * per; j++) { object.put("id", j); object.put("money", j); jedis.lpush(hongBaoList, object.toString()); } latch.countDown(); jedis.close(); } }; thread.start(); } latch.await(); }
From source file:com.jkoolcloud.tnt4j.streams.StreamsAgent.java
private static void stopStreams() { if (streamThreads != null) { LOGGER.log(OpLevel.INFO, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsAgent.stopping.streams"), streamThreads.getName()); Thread[] atl = new Thread[streamThreads.activeCount()]; streamThreads.enumerate(atl, false); List<StreamThread> stl = new ArrayList<>(atl.length); for (Thread t : atl) { if (t instanceof StreamThread) { stl.add((StreamThread) t); }//from w w w. j a v a 2 s .c o m } if (stl.isEmpty()) { LOGGER.log(OpLevel.INFO, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsAgent.streams.stop.empty")); } else { LOGGER.log(OpLevel.INFO, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsAgent.streams.stop.start"), stl.size()); CountDownLatch streamsCompletionSignal = new CountDownLatch(stl.size()); long t1 = System.currentTimeMillis(); for (StreamThread st : stl) { st.addCompletionLatch(streamsCompletionSignal); st.getTarget().stop(); } try { streamsCompletionSignal.await(); } catch (InterruptedException exc) { } LOGGER.log(OpLevel.INFO, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsAgent.streams.stop.complete"), (System.currentTimeMillis() - t1)); } } }
From source file:org.coffeeking.controller.service.util.ConnectedCupServiceUtils.java
public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, boolean fireAndForgot) throws DeviceManagementException { String responseMsg = ""; String urlString = ConnectedCupConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; if (log.isDebugEnabled()) { log.debug(urlString);//from w ww .j a va 2 s . co m } if (!fireAndForgot) { HttpURLConnection httpConnection = getHttpConnection(urlString); try { httpConnection.setRequestMethod(HttpMethod.GET); } catch (ProtocolException e) { String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:" + urlString; log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } responseMsg = readResponseFromGetRequest(httpConnection); } else { CloseableHttpAsyncClient httpclient = null; try { httpclient = HttpAsyncClients.createDefault(); httpclient.start(); HttpGet request = new HttpGet(urlString); final CountDownLatch latch = new CountDownLatch(1); Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { latch.countDown(); } @Override public void failed(Exception e) { latch.countDown(); } @Override public void cancelled() { latch.countDown(); } }); latch.await(); } catch (InterruptedException e) { if (log.isDebugEnabled()) { log.debug("Sync Interrupted"); } } finally { try { if (httpclient != null) { httpclient.close(); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed on close"); } } } } return responseMsg; }
From source file:org.usergrid.benchmark.commands.queue.QueueReader.java
@Override protected void doWork(CommandLine line, Queue<TestEvent> queue, String hostName, int workers, int count) throws Exception { CountDownLatch latch = new CountDownLatch(count * workers); queue.observe(new EventListener(latch, readsTimer, readLogger, queue)); latch.await(); writeTimerData(readsTimer);/*from w w w .j a va 2s. c o m*/ }
From source file:com.fusesource.forge.jmstest.threading.SteppablePool.java
public void waitUntilFinished() { CountDownLatch latch = new CountDownLatch(1); latches.add(latch);/* w ww . ja v a 2s. c o m*/ try { latch.await(); } catch (InterruptedException ie) { } }
From source file:com.dangdang.ddframe.job.api.type.dataflow.executor.DataflowJobExecutor.java
private void latchAwait(final CountDownLatch latch) { try {/*w w w . j a va2s .c o m*/ latch.await(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } }
From source file:com.facebook.LinkBench.LinkBenchDriver.java
/** * Start all runnables at the same time. Then block till all * tasks are completed. Returns the elapsed time (in millisec) * since the start of the first task to the completion of all tasks. *///from ww w . j ava2s . c o m static long concurrentExec(final List<? extends Runnable> tasks) throws Throwable { final CountDownLatch startSignal = new CountDownLatch(tasks.size()); final CountDownLatch doneSignal = new CountDownLatch(tasks.size()); final AtomicLong startTime = new AtomicLong(0); for (final Runnable task : tasks) { new Thread(new Runnable() { @Override public void run() { /* * Run a task. If an uncaught exception occurs, bail * out of the benchmark immediately, since any results * of the benchmark will no longer be valid anyway */ try { startSignal.countDown(); startSignal.await(); long now = System.currentTimeMillis(); startTime.compareAndSet(0, now); task.run(); } catch (Throwable e) { Logger threadLog = Logger.getLogger(ConfigUtil.LINKBENCH_LOGGER); threadLog.error("Unrecoverable exception in worker thread:", e); Runtime.getRuntime().halt(1); } doneSignal.countDown(); } }).start(); } doneSignal.await(); // wait for all threads to finish long endTime = System.currentTimeMillis(); return endTime - startTime.get(); }