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:com.test.database.jedis.TestJedisEvalLua.java

public static void generateTestData() throws InterruptedException {
    Jedis jedis = new Jedis(host, port);
    jedis.flushAll();//  w ww .  ja  v  a  2 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:org.auraframework.test.AuraTestingUtil.java

/**
 * Clear cached defs from the system. When mocking a def, if the def has already been cached, as itself, or as part
 * of a preloaded set, the mock will not be effective, so it's safer to clear any cached defs after setting up mocks
 * but before executing a test. This relies on source change notifications to get the servlets to clear their
 * caches./*w w w  . ja  v  a  2s.  c o  m*/
 * 
 * @param defs the Definitions to be cleared from any caches
 * @throws InterruptedException
 */
public static <T extends Definition> void clearCachedDefs(Collection<T> defs) throws Exception {
    if (defs == null || defs.isEmpty()) {
        return;
    }

    // Get the Descriptors for the provided Definitions
    final DefinitionService definitionService = Aura.getDefinitionService();
    final Set<DefDescriptor<?>> cached = Sets.newHashSet();
    for (T def : defs) {
        if (def != null) {
            cached.add(def.getDescriptor());
        }
    }

    // Wait for the change notifications to get processed. We expect listeners to get processed in the order in
    // which they subscribe.
    final CountDownLatch latch = new CountDownLatch(cached.size());
    SourceListener listener = new SourceListener() {
        private Set<DefDescriptor<?>> descriptors = Sets.newHashSet(cached);

        @Override
        public void onSourceChanged(DefDescriptor<?> source, SourceMonitorEvent event, String filePath) {
            if (descriptors.remove(source)) {
                latch.countDown();
            }
            if (descriptors.isEmpty()) {
                definitionService.unsubscribeToChangeNotification(this);
            }
        }
    };
    definitionService.subscribeToChangeNotification(listener);
    for (DefDescriptor<?> desc : cached) {
        definitionService.onSourceChanged(desc, SourceMonitorEvent.CHANGED, null);
    }
    if (!latch.await(CACHE_CLEARING_TIMEOUT_SECS, TimeUnit.SECONDS)) {
        throw new AuraRuntimeException(
                String.format("Timed out after %s seconds waiting for cached Aura definitions to clear: %s",
                        CACHE_CLEARING_TIMEOUT_SECS, defs));
    }
}

From source file:com.mgmtp.perfload.core.daemon.LtDaemon.java

public static void shutdownDaemon(final int port) {
    final CountDownLatch latch = new CountDownLatch(1);

    Client client = new DefaultClient("shutdownClient", "localhost", port);
    client.addClientMessageListener(new ClientMessageListener() {
        @Override// w ww . j a v  a 2  s  . c om
        public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) {
            final Payload payload = (Payload) e.getMessage();
            if (payload.getPayloadType() == PayloadType.SHUTDOWN_DAEMON) {
                log().info("Successfully requested shutdown.");
                latch.countDown();
            }
        }
    });

    log().info("Connecting to daemon at port {}...", port);
    client.connect();
    if (client.isConnected()) {
        client.sendMessage(new Payload(PayloadType.SHUTDOWN_DAEMON));
        client.disconnect();
    } else {
        log().info("Could not connect to daemon. Daemon probably not running.");
    }
    log().info("Good bye.");
}

From source file:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java

/**
 * Runs a number of threads which generate metrics.
 *///from   w  ww. ja v  a  2 s.  c om
public static void generateMetrics(final MetricRegistry metrics, final long metricsToGenerate, final int period,
        final TimeUnit periodTimeUnit, HadoopMetrics2Reporter metrics2Reporter, int numThreads)
        throws Exception {
    final ScheduledExecutorService pool = Executors.newScheduledThreadPool(numThreads);
    final CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        final int id = i;
        final int halfPeriod = (period / 2);
        Runnable task = new Runnable() {
            private long executions = 0;
            final Random r = new Random();

            @Override
            public void run() {
                if (executions >= metricsToGenerate) {
                    return;
                }
                metrics.counter("foo counter thread" + id).inc();
                executions++;
                if (executions < metricsToGenerate) {
                    pool.schedule(this, period + r.nextInt(halfPeriod), periodTimeUnit);
                } else {
                    latch.countDown();
                }
            }
        };
        pool.schedule(task, period, periodTimeUnit);
    }

    while (!latch.await(2, TimeUnit.SECONDS)) {
        metrics2Reporter.printQueueDebugMessage();
    }

    pool.shutdown();
    pool.awaitTermination(5000, TimeUnit.SECONDS);
}

From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java

/**
 * updateComment updates the text field of a comment
 * @throws InterruptedException /*www . j  a  v  a2s . c o m*/
 */
public static void updateComment(final Comment comment, final String str)
        throws ClientProtocolException, IOException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    Thread thread = new Thread() {
        @SuppressWarnings("hiding")
        @Override
        public void run() {
            HttpPost updateRequest = new HttpPost(updateAddress + comment.getUuid() + "/_update/");
            String query = "{\"script\" : \"ctx._source." + str + "}";
            StringEntity stringentity;
            try {
                stringentity = new StringEntity(query);
                updateRequest.setHeader("Accept", "application/json");
                updateRequest.setEntity(stringentity);

                latch.countDown();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    thread.start();
    latch.await();
}

From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host/*from ww w.j  av a 2 s .co m*/
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(
                String.format("One or several of service(s) %s not available", Utils.toJson(serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:com.frostwire.android.MediaScanner.java

private static void scanFiles(final Context context, List<String> paths, int retries) {
    if (paths.size() == 0) {
        return;//from   w  w  w .  j  a v  a  2s. c o m
    }

    LOG.info("About to scan files n: " + paths.size() + ", retries: " + retries);

    final LinkedList<String> failedPaths = new LinkedList<>();

    final CountDownLatch finishSignal = new CountDownLatch(paths.size());

    MediaScannerConnection.scanFile(context, paths.toArray(new String[0]), null, (path, uri) -> {
        try {
            boolean success = true;
            if (uri == null) {
                success = false;
                failedPaths.add(path);
            } else {
                // verify the stored size four faulty scan
                long size = getSize(context, uri);
                if (size == 0) {
                    LOG.warn("Scan returned an uri but stored size is 0, path: " + path + ", uri:" + uri);
                    success = false;
                    failedPaths.add(path);
                }
            }
            if (!success) {
                LOG.info("Scan failed for path: " + path + ", uri: " + uri);
            }
        } finally {
            finishSignal.countDown();
        }
    });

    try {
        finishSignal.await(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // ignore
    }

    if (failedPaths.size() > 0 && retries > 0) {
        // didn't want to do this, but there is a serious timing issue with the SD
        // and storage in general
        SystemClock.sleep(2000);
        scanFiles(context, failedPaths, retries - 1);
    }
}

From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java

public static <H extends ServiceHost> void deleteAllDocuments(H host, String referrer, long timeout,
        TimeUnit timeUnit) throws Throwable {
    QueryTask.Query selfLinkClause = new QueryTask.Query()
            .setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK).setTermMatchValue("*")
            .setTermMatchType(QueryTask.QueryTerm.MatchType.WILDCARD);

    QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification();
    querySpecification.query.addBooleanClause(selfLinkClause);
    QueryTask queryTask = QueryTask.create(querySpecification).setDirect(true);

    NodeGroupBroadcastResponse queryResponse = ServiceHostUtils.sendBroadcastQueryAndWait(host, referrer,
            queryTask);/*from ww  w . ja va2 s. co m*/

    Set<String> documentLinks = QueryTaskUtils.getBroadcastQueryResults(queryResponse);

    if (documentLinks == null || documentLinks.size() <= 0) {
        return;
    }

    CountDownLatch latch = new CountDownLatch(1);

    OperationJoin.JoinedCompletionHandler handler = new OperationJoin.JoinedCompletionHandler() {
        @Override
        public void handle(Map<Long, Operation> ops, Map<Long, Throwable> failures) {
            if (failures != null && !failures.isEmpty()) {
                for (Throwable e : failures.values()) {
                    logger.error("deleteAllDocuments failed", e);
                }
            }
            latch.countDown();
        }
    };

    Collection<Operation> deletes = new LinkedList<>();
    for (String documentLink : documentLinks) {
        Operation deleteOperation = Operation.createDelete(UriUtils.buildUri(host, documentLink)).setBody("{}")
                .setReferer(UriUtils.buildUri(host, referrer));
        deletes.add(deleteOperation);
    }

    OperationJoin join = OperationJoin.create(deletes);
    join.setCompletion(handler);
    join.sendWith(host);
    if (!latch.await(timeout, timeUnit)) {
        throw new TimeoutException(String
                .format("Deletion of all documents timed out. Timeout:{%s}, TimeUnit:{%s}", timeout, timeUnit));
    }
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host//from w w  w  . ja v a  2s . c om
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(String.format("One or several of service(s) %s not available",
                Utils.toJson(false, false, serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:thingynet.cache.CacheClientService.java

void notifyCachePut(String key) {
    if (key != null) {
        rwl.writeLock().lock();//from  w  w w  .ja v a 2 s  .  c  o m
        CountDownLatch latch = latches.remove(key);
        if (latch != null) {
            latch.countDown();
        }
        rwl.writeLock().unlock();
    }
}