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) 

Source Link

Document

Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and does not perform a predefined action when the barrier is tripped.

Usage

From source file:Main.java

public static void main(String[] args) {
    CyclicBarrier barrier = new CyclicBarrier(2);
    new Thread() {
        @Override/*from  ww  w .  ja  v  a  2  s.c  om*/
        public void run() {
            try {
                System.out.println("in thread, before the barrier");
                barrier.await();
                System.out.println("in thread, after the barrier");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();

    try {
        System.out.println("main thread, before barrier");
        barrier.await();

        System.out.println("main thread, after barrier");
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) {
    cb = new CyclicBarrier(2);
    Timer t = new Timer();
    t.schedule(new MyTimerTask(cb), 1000, 1000);
    while (true) {
        try {// w  w w .ja  va  2s  . c  o  m
            cb.await();
        } catch (Exception e) {
        }
        System.out.println("main");
    }
}

From source file:Main.java

public static void main(String[] args) {
    CyclicBarrier barrier = new CyclicBarrier(2);
    Receiver receiver = new Receiver(barrier);
    Sender sender = new Sender(barrier);
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.submit(receiver);/*from w ww .j  a v a2 s.  c o  m*/
    executor.submit(sender);
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * @param args there are no arguments needed
 * @throws Exception if error occurs during tests
 *///from w ww. j  a va  2  s . c  o m
public static void main(String[] args) throws Exception {
    if (!parseInputArgs(args)) {
        usage();
        System.exit(-1);
    }
    if (sHelp) {
        usage();
        System.exit(0);
    }

    CommonUtils.warmUpLoop();

    for (int i = 0; i < sIterations; ++i) {
        final AtomicInteger count = new AtomicInteger(0);
        final CyclicBarrier barrier = new CyclicBarrier(sConcurrency);
        ExecutorService executorService = Executors.newFixedThreadPool(sConcurrency);
        final AtomicLong runtime = new AtomicLong(0);
        for (int j = 0; j < sConcurrency; ++j) {
            switch (sType) {
            case READ:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            readFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to read file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            case WRITE:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            writeFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to write file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            default:
                throw new RuntimeException("Unsupported type.");
            }
        }
        executorService.shutdown();
        Preconditions.checkState(executorService.awaitTermination(1, TimeUnit.HOURS));
        double time = runtime.get() * 1.0 / sConcurrency / Constants.SECOND_NANO;
        System.out.printf("Iteration: %d; Duration: %f seconds; Aggregated throughput: %f GB/second.%n", i,
                time, sConcurrency * 1.0 * sFileSize / time / Constants.GB);
    }
}

From source file:Main.java

public void start(String[] args) {

    barrier = new CyclicBarrier(args.length);

    for (final String site : args)
        new Thread() {
            public void run() {
                while (true) {
                    long time = timeConnect(site);
                    results.add(new Result(time, site));
                    try {
                        barrier.await(99, TimeUnit.SECONDS);
                    } catch (BrokenBarrierException e) {
                        return;
                    } catch (Exception e) {
                        return;
                    }/*from ww w.  ja  v  a  2s . com*/
                }
            }
        }.start();
}

From source file:io.osv.LoggingIsolationTest.java

@Test
public void testLoggerLevelChangesAreIsolated() throws Throwable {
    File log1 = newTemporaryFile();
    File log2 = newTemporaryFile();

    Context ctx1 = runIsolate(LoggingProcess.class, log1.getAbsolutePath(), LOGGER_NAME, "INFO", "ctx1");
    Context ctx2 = runIsolate(LoggingProcess.class, log2.getAbsolutePath(), LOGGER_NAME, "WARNING", "ctx2");

    CyclicBarrier barrier = new CyclicBarrier(2);
    ctx1.send(barrier);/*from  w  w  w . jav  a 2s .co  m*/
    ctx2.send(barrier);

    ctx1.join();
    ctx2.join();

    assertThat(readLines(log1)).hasSize(4).contains("INFO: ctx1").contains("WARNING: ctx1");

    assertThat(readLines(log2)).hasSize(2).contains("WARNING: ctx2").excludes("INFO: ctx2");
}

From source file:paxos.VoteLeaderListener2.java

/**
 * //from   w w w  .j  av  a  2  s  . com
 * @param target The Runnable target to be executed
 * @param timeout The time in milliseconds before target will be interrupted or stopped
 * @param forceStop If true, will Thread.stop() this target instead of just interrupt() 
 */
public VoteLeaderListener2(Runnable target, long timeout, boolean forceStop) {
    this.timeout = timeout;
    this.forceStop = forceStop;

    this.target = new Thread(target);
    this.interrupter = new Thread(new Interrupter());

    barrier = new CyclicBarrier(2); // There will always be just 2 threads waiting on this barrier
}

From source file:com.googlecode.ehcache.annotations.integration.RefreshingSelfPopulatingTest.java

/**
 * Verify that setting selfPopulating=true will guarantee only 1 invocation
 * of the cached method./*w ww.j a  v  a2s .  com*/
 * 
 * @throws Exception
 */
@Test //(timeout=1000)
public void testSelfPopulatingTrue() throws Exception {
    final CountDownLatch threadRunningLatch = new CountDownLatch(2);
    final CyclicBarrier proceedLatch = new CyclicBarrier(2);
    this.refreshingSelfPopulatingTestInterface.setThreadRunningLatch(threadRunningLatch);
    this.refreshingSelfPopulatingTestInterface.setProccedLatch(proceedLatch);

    Assert.assertEquals(0, this.refreshingSelfPopulatingTestInterface.getBlockingAInvocationCount());

    final ThreadGroupRunner threadGroup = new ThreadGroupRunner("testSelfPopulatingTrue-", true);

    threadGroup.addTask(1, new Runnable() {
        public void run() {
            threadRunningLatch.countDown();
            logger.trace("Calling blockingA(test2)");
            refreshingSelfPopulatingTestInterface.blockingA("test2");
        }
    });

    threadGroup.start();

    // wait for both threads to get going
    logger.trace("Waiting for threads to start");
    threadRunningLatch.await();

    // Let both threads complete
    logger.trace("Signal threads to proceed");
    proceedLatch.await();

    logger.trace("Waiting for threads to complete");
    threadGroup.join();

    // verify only 1 call between method A and method B
    Assert.assertEquals(1, this.refreshingSelfPopulatingTestInterface.getBlockingAInvocationCount());

    Thread.sleep(1500);
    proceedLatch.await();

    //Wait for the refresh thread to complete
    Thread.sleep(10);

    Assert.assertEquals(2, this.refreshingSelfPopulatingTestInterface.getBlockingAInvocationCount());

}

From source file:com.newlandframework.avatarmq.core.AckMessageCache.java

public void parallelDispatch(LinkedList<String> list) {
    List<Callable<Long>> tasks = new ArrayList<Callable<Long>>();
    List<Future<Long>> futureList = new ArrayList<Future<Long>>();
    int startPosition = 0;
    Pair<Integer, Integer> pair = calculateBlocks(list.size(), list.size());
    int numberOfThreads = pair.getRight();
    int blocks = pair.getLeft();

    barrier = new CyclicBarrier(numberOfThreads);

    for (int i = 0; i < numberOfThreads; i++) {
        String[] task = new String[blocks];
        System.arraycopy(list.toArray(), startPosition, task, 0, blocks);
        tasks.add(new AckMessageTask(barrier, task));
        startPosition += blocks;//from www  .java 2 s.c o m
    }

    ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
    try {
        futureList = executor.invokeAll(tasks);
    } catch (InterruptedException ex) {
        Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (Future<Long> longFuture : futureList) {
        try {
            succTaskCount += longFuture.get();
        } catch (InterruptedException ex) {
            Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.jboss.rusheye.result.statistics.TestOverallStatistics.java

@Test
public void testOverallStatistics() throws IOException, InterruptedException, BrokenBarrierException {
    List<String> list = new LinkedList<String>();
    PipedWriter pipedWriter = new PipedWriter();
    CyclicBarrier barrier = new CyclicBarrier(2);

    new Thread(new StreamToListWrapper(pipedWriter, list, barrier)).start();

    when(properties.getProperty("overall-statistics-output")).thenReturn(pipedWriter);
    when(test.getName()).thenReturn("testName");
    when(test.getPatterns()).thenReturn(Arrays.asList(pattern));
    when(pattern.getName()).thenReturn("patternName");
    when(pattern.getConclusion()).thenReturn(ResultConclusion.PERCEPTUALLY_SAME);
    when(pattern.getOutput()).thenReturn("someLocation");

    overallStatistics.setProperties(properties);

    overallStatistics.onPatternCompleted(pattern);

    overallStatistics.onTestCompleted(test);
    barrier.await();// w ww  .  ja va2 s. c o  m
    Assert.assertTrue(list.contains("[ PERCEPTUALLY_SAME ] testName"));

    overallStatistics.onSuiteCompleted();
    barrier.await();
    Assert.assertTrue(list.contains("  Overall Statistics:"));
    Assert.assertTrue(list.contains("  PERCEPTUALLY_SAME: 1"));
}