Example usage for java.util.concurrent CyclicBarrier CyclicBarrier

List of usage examples for java.util.concurrent CyclicBarrier CyclicBarrier

Introduction

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

Prototype

public CyclicBarrier(int parties, Runnable barrierAction) 

Source Link

Document

Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and which will execute the given barrier action when the barrier is tripped, performed by the last thread entering the barrier.

Usage

From source file:com.mgmtp.perfload.core.client.util.concurrent.DelayingExecutorServiceTest.java

@Test
public void testWithDelay() throws InterruptedException, BrokenBarrierException {
    DelayingExecutorService execSrv = new DelayingExecutorService();

    final StopWatch sw = new StopWatch();

    final CyclicBarrier stopBarrier = new CyclicBarrier(11, new Runnable() {
        @Override//  w  w  w .  j ava2  s  .c  o  m
        public void run() {
            sw.stop();
        }
    });

    sw.start();

    final long taskSleepMillis = 75L;
    long delayMultiplier = 50L;
    int loopMax = 10;

    for (int i = 0; i < loopMax; ++i) {
        Callable<Void> c = new Callable<Void>() {
            @Override
            public Void call() {
                try {
                    Thread.sleep(taskSleepMillis);
                    stopBarrier.await();
                } catch (Exception ex) {
                    throw new AssertionError(ex);
                }
                return null;
            }
        };

        long delay = delayMultiplier * i;

        ScheduledFuture<?> future = execSrv.schedule(c, delay, TimeUnit.MILLISECONDS);
        long actualDelay = future.getDelay(TimeUnit.MILLISECONDS);

        // compare with epsilon to make up for bad accuracy
        assertTrue(abs(delay - actualDelay) < EPSILON);
    }

    stopBarrier.await();

    long actualTime = sw.getTime();
    long expectedTime = delayMultiplier * (loopMax - 1) + taskSleepMillis;

    // compare with epsilon to make up for bad accuracy
    assertTrue(abs(actualTime - expectedTime) < EPSILON);
}

From source file:org.springframework.data.hadoop.mapreduce.JobRunner.java

@Override
public Object getObject() throws Exception {
    if (!executed) {
        executed = true;//from w w  w  . ja  va2s.  co  m

        final CountDownLatch cdl = new CountDownLatch(1);
        cb = new CyclicBarrier(jobs.size(), new Runnable() {

            @Override
            public void run() {
                log.info("All jobs have completion.");
                cdl.countDown();
            }
        });

        ExecutorService es = Executors.newFixedThreadPool(jobs.size());
        for (JobConf job : jobs) {
            es.submit(new JobWorker(job));
        }

        if (waitForJobs) {
            log.info("Waiting all jobs completion signal....");
            cdl.await();
        } else {
            log.info("No need wait any job completio, do continue.");
            cdl.countDown();
        }
    }

    return (waitForJobs ? true : null);
}

From source file:it.cnr.icar.eric.server.query.federation.FederatedQueryProcessor.java

/**
 * Submits an AdhocQueryRequest to all Registries thare are members of specified federation.
 *
 * @param user/*from   w  w  w .  j a va  2  s  . co  m*/
 * @param adhocQueryRequest the request sent to every registry ias a parrallel distrubuted query.
 */
public AdhocQueryResponse submitAdhocQuery(final ServerRequestContext context) throws RegistryException {

    this.adhocQueryRequest = (AdhocQueryRequest) context.getCurrentRegistryRequest();
    try {
        //Reset federated flag before doing federated query to avoid infinite loop
        adhocQueryRequest.setFederated(false);

        //Reset federation flag before doing federated query to avoid potential 
        //for implementations to interpret non-null values as implying federated query
        adhocQueryRequest.setFederation(null);

        // Create a barrier for all worker threads
        log.trace("Dispatching federated query to " + members.size() + " member registries.");
        CyclicBarrier barrier = new CyclicBarrier(members.size(), new Runnable() {
            public void run() {
                retrieveResults(context);
            }
        });

        ThreadGroup threadGroup = new ThreadGroup("federatedQuery");
        // Send a request to all destinations
        Iterator<RegistryType> i = members.iterator();
        while (i.hasNext()) {
            RegistryType registry = i.next();
            FederatedQueryWorker worker = new FederatedQueryWorker(barrier, registry, TIMEOUT_CONSTANT,
                    context.getUser(), adhocQueryRequest);
            workers.add(worker);
            //Thread thread = new Thread(threadGroup, worker);
            Thread thread = new Thread(threadGroup, worker, "Federated_Query_" + registry.getId());
            threads.add(thread);
            log.trace("Dispatching query to registry with id: " + registry.getId() + " name: "
                    + bu.getInternationalStringAsString(registry.getName()));
            thread.start();
        }

        Iterator<Thread> i1 = threads.iterator();
        while (i1.hasNext()) {
            Thread thread = i1.next();
            // Wait until all threads have finished.
            // CAVEAT: The timeouts will add up, max. waiting time is (number of threads) * (timeout)
            try {
                thread.join(TIMEOUT_CONSTANT);
            } catch (InterruptedException e) {
                //TODO: Try to kill the thread somehow
            }
        }
    } catch (JAXRException e) {
        //This exception is thrown potentially (unlikely) by bu.getInternationalStringAsString
        throw new RegistryException(e);
    }

    return getUnifiedResponse();
}