Example usage for java.util.concurrent CountDownLatch countDown

List of usage examples for java.util.concurrent CountDownLatch countDown

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch countDown.

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

From source file:Main.java

/**
 * Performs a drag between the given coordinates, specified relative to the given view.
 * This is safe to call from the instrumentation thread and will invoke the drag
 * asynchronously.//from   w w w.j  av a 2  s .c o m
 *
 * @param view The view the coordinates are relative to.
 * @param fromX The relative x-coordinate of the start point of the drag.
 * @param toX The relative x-coordinate of the end point of the drag.
 * @param fromY The relative y-coordinate of the start point of the drag.
 * @param toY The relative y-coordinate of the end point of the drag.
 * @param stepCount The total number of motion events that should be generated during the drag.
 * @param completionLatch The .countDown method is called on this latch once the drag finishes.
 */
public static void dragCompleteView(final View view, final int fromX, final int toX, final int fromY,
        final int toY, final int stepCount, final CountDownLatch completionLatch) {
    view.post(new Runnable() {
        @Override
        public void run() {
            long downTime = dragStart(view, fromX, fromY);
            dragTo(view, fromX, toX, fromY, toY, stepCount, downTime);
            dragEnd(view, toX, toY, downTime);
            if (completionLatch != null) {
                completionLatch.countDown();
            }
        }
    });
}

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

private static SuiteListener countMessages(SuiteListener target, CountDownLatch latch) {
    SuiteListenerEventizer eventizer = new SuiteListenerEventizer();
    MessageSender<Event<SuiteListener>> backend = eventizer.newBackend(target);
    MessageSender<Event<SuiteListener>> counter = message -> {
        backend.send(message);// w  w  w . j av  a  2  s . c o  m
        latch.countDown();
    };
    return eventizer.newFrontend(counter);
}

From source file:io.servicecomb.foundation.vertx.VertxUtils.java

public static <VERTICLE extends AbstractVerticle> boolean blockDeploy(Vertx vertx, Class<VERTICLE> cls,
        DeploymentOptions options) throws InterruptedException {
    Holder<Boolean> result = new Holder<>();

    CountDownLatch latch = new CountDownLatch(1);
    vertx.deployVerticle(cls.getName(), options, ar -> {
        result.value = ar.succeeded();//from w ww . j a  v  a 2 s  .co m

        if (ar.failed()) {
            LOGGER.error("deploy vertx failed, cause ", ar.cause());
        }

        latch.countDown();
    });

    latch.await();

    return result.value;
}

From source file:com.twitter.distributedlog.basic.MultiReader.java

private static void readLoop(final AsyncLogReader reader, final CountDownLatch keepAliveLatch) {
    final FutureEventListener<LogRecordWithDLSN> readListener = new FutureEventListener<LogRecordWithDLSN>() {
        @Override//from ww  w  .j ava 2s .  co  m
        public void onFailure(Throwable cause) {
            System.err.println("Encountered error on reading records from stream " + reader.getStreamName());
            cause.printStackTrace(System.err);
            keepAliveLatch.countDown();
        }

        @Override
        public void onSuccess(LogRecordWithDLSN record) {
            System.out
                    .println("Received record " + record.getDlsn() + " from stream " + reader.getStreamName());
            System.out.println("\"\"\"");
            System.out.println(new String(record.getPayload(), UTF_8));
            System.out.println("\"\"\"");
            reader.readNext().addEventListener(this);
        }
    };
    reader.readNext().addEventListener(readListener);
}

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);//  www  .j  a v a 2 s. com
    }

    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.microsoft.office.core.EventsAsyncTestCase.java

@BeforeClass
public static void retrieveCalendar() throws Exception {
    final ICalendars cals = Me.getCalendars();
    final CountDownLatch cdl = new CountDownLatch(1);
    // an empty iterator will be returned for any entity set unless you call fetch()
    Futures.addCallback(cals.fetchAsync(), new FutureCallback<Void>() {
        @Override// w  w w .jav a 2  s  . c om
        public void onFailure(Throwable t) {
            cdl.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            Iterator<ICalendar> iterator = cals.iterator();
            if (iterator.hasNext()) {
                calendar = iterator.next();
            }
            cdl.countDown();
        }
    });

    cdl.await(60000, TimeUnit.MILLISECONDS);
    if (calendar == null) {
        fail("No calendar found");
    }
}

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   ww w  .  j a va 2  s .c om
    }

    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.twitter.distributedlog.basic.MultiReader.java

private static void readLoop(final DistributedLogManager dlm, final DLSN dlsn,
        final CountDownLatch keepAliveLatch) {
    System.out.println("Wait for records from " + dlm.getStreamName() + " starting from " + dlsn);
    dlm.openAsyncLogReader(dlsn).addEventListener(new FutureEventListener<AsyncLogReader>() {
        @Override//  w ww . j av a 2 s  .c om
        public void onFailure(Throwable cause) {
            System.err.println("Encountered error on reading records from stream " + dlm.getStreamName());
            cause.printStackTrace(System.err);
            keepAliveLatch.countDown();
        }

        @Override
        public void onSuccess(AsyncLogReader reader) {
            System.out.println("Open reader to read records from stream " + reader.getStreamName());
            readLoop(reader, keepAliveLatch);
        }
    });
}

From source file:com.twitter.distributedlog.LocalDLMEmulator.java

public static ZooKeeper connectZooKeeper(String zkHost, int zkPort, int zkTimeoutSec)
        throws IOException, KeeperException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final String zkHostPort = zkHost + ":" + zkPort;

    ZooKeeper zkc = new ZooKeeper(zkHostPort, zkTimeoutSec * 1000, new Watcher() {
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                latch.countDown();
            }//from   w ww .  j a  va 2 s.  c  o  m
        }
    });
    if (!latch.await(zkTimeoutSec, TimeUnit.SECONDS)) {
        throw new IOException("Zookeeper took too long to connect");
    }
    return zkc;
}

From source file:io.coala.capability.online.FluentHCOnlineCapability.java

private static void scheduleCountdown(final CountDownLatch latch) {
    Schedulers.io().createWorker().schedule(new Action0() {
        @Override/*ww w.  j  a  va  2  s. c om*/
        public void call() {
            latch.countDown();
        }
    });
}