Example usage for java.util.concurrent CyclicBarrier await

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

Introduction

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

Prototype

public int await() throws InterruptedException, BrokenBarrierException 

Source Link

Document

Waits until all #getParties parties have invoked await on this barrier.

Usage

From source file:io.druid.indexer.HdfsClasspathSetupTest.java

@Test
public void testConcurrentUpload()
        throws IOException, InterruptedException, ExecutionException, TimeoutException {
    final int concurrency = 10;
    ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(concurrency));
    // barrier ensures that all jobs try to add files to classpath at same time.
    final CyclicBarrier barrier = new CyclicBarrier(concurrency);
    final DistributedFileSystem fs = miniCluster.getFileSystem();
    final Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName());
    List<ListenableFuture<Boolean>> futures = new ArrayList<>();

    for (int i = 0; i < concurrency; i++) {
        futures.add(pool.submit(new Callable() {
            @Override/*from  www.  j  a v a  2 s. c o  m*/
            public Boolean call() throws Exception {
                int id = barrier.await();
                Job job = Job.getInstance(conf, "test-job-" + id);
                Path intermediatePathForJob = new Path(intermediatePath, "job-" + id);
                JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePathForJob, fs, job);
                // check file gets uploaded to final HDFS path
                Assert.assertTrue(fs.exists(expectedJarPath));
                // check that the intermediate file is not present
                Assert.assertFalse(fs.exists(new Path(intermediatePathForJob, dummyJarFile.getName())));
                // check file gets added to the classpath
                Assert.assertEquals(expectedJarPath.toString(),
                        job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES));
                return true;
            }
        }));
    }

    Futures.allAsList(futures).get(30, TimeUnit.SECONDS);

    pool.shutdownNow();
}

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// www . ja  v  a  2  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:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java

private void breakBarrier(CyclicBarrier barrier) throws BrokenBarrierException {
    final Thread testThread = Thread.currentThread();
    Thread interruptThread = new Thread() {
        @Override/*from w  w w.j av  a2s .  c o  m*/
        public void run() {
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            testThread.interrupt();
        }
    };
    interruptThread.start();

    try {
        barrier.await();
        Assert.fail();
    } catch (InterruptedException e) {
    }
}

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testMultipleThreads() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final List<Future<Map<Integer, Integer>>> futures = new ArrayList<Future<Map<Integer, Integer>>>();

    for (int i = 0; i < 5; i++) {
        futures.add(threadPool.submit(new Callable<Map<Integer, Integer>>() {

            @Override/*from w ww  .  j a va  2  s.co  m*/
            public Map<Integer, Integer> call() throws Exception {

                barrier.await();

                TestWorker worker = new TestWorker();

                while (!stop.get()) {
                    worker.process();
                }

                return worker.map;
            }
        }));
    }

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> totalMap = getTotalMap(futures);
    checkValues(new ArrayList<Integer>(totalMap.values()));
}

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testMultipleThreadsWithElementAdd() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final List<Future<Map<Integer, Integer>>> futures = new ArrayList<Future<Map<Integer, Integer>>>();

    for (int i = 0; i < 5; i++) {
        futures.add(threadPool.submit(new Callable<Map<Integer, Integer>>() {

            @Override//from  www.j a va 2  s .c om
            public Map<Integer, Integer> call() throws Exception {

                barrier.await();

                TestWorker worker = new TestWorker();

                while (!stop.get()) {
                    worker.process();
                }

                return worker.map;
            }
        }));
    }

    Thread.sleep(200);

    List<Integer> newList = new ArrayList<Integer>(iList);
    for (int i = 10; i < 15; i++) {
        newList.add(i);
    }

    cList.swapWithList(newList);

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> result = getTotalMap(futures);

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
            return input < 10;
        }
    });

    checkValues(new ArrayList<Integer>(subMap.values()));

    subMap = CollectionUtils.difference(result, subMap).entriesOnlyOnLeft();
    checkValues(new ArrayList<Integer>(subMap.values()));
}

From source file:com.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testMultipleThreadsWithElementsRemoved() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final List<Future<Map<Integer, Integer>>> futures = new ArrayList<Future<Map<Integer, Integer>>>();

    for (int i = 0; i < 5; i++) {
        futures.add(threadPool.submit(new Callable<Map<Integer, Integer>>() {

            @Override/*w w  w .  j a  v a  2 s. co  m*/
            public Map<Integer, Integer> call() throws Exception {

                barrier.await();

                TestWorker worker = new TestWorker();

                while (!stop.get()) {
                    worker.process();
                }

                return worker.map;
            }
        }));
    }

    Thread.sleep(200);

    List<Integer> newList = new ArrayList<Integer>(iList);

    final List<Integer> removedElements = new ArrayList<Integer>();
    removedElements.add(newList.remove(2));
    removedElements.add(newList.remove(5));
    removedElements.add(newList.remove(6));

    cList.swapWithList(newList);

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> result = getTotalMap(futures);

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {

        @Override
        public boolean apply(Integer x) {
            return !removedElements.contains(x);
        }
    });

    checkValues(new ArrayList<Integer>(subMap.values()));
}

From source file:uk.ac.gla.terrier.probos.cli.pbsdsh.java

@Override
public int run(String[] args) throws Exception {

    Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
    Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
    LOG.debug("Executing with tokens:");
    while (iter.hasNext()) {
        Token<?> token = iter.next();
        LOG.debug(token.toString());//  w ww.ja v a  2 s .  c  o m
        if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
            iter.remove();
        }
    }

    Options options = new Options();
    options.addOption("h", true, "Specify hostname.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    final String[] dibcommand = cmd.getArgs();

    int jobId = getJobId();
    if (jobId == -1) {
        System.err.println("PBS: PBS_JOBID not set");
        return 1;
    }
    String[] hosts;

    PBSJobStatusDistributed d = (PBSJobStatusDistributed) c.getJobStatus(jobId, 5);
    if (d.getState() == '?') {
        System.err.println("PBS: Job " + jobId + " was lost");
        return -1;
    }
    if (d.getState() != 'R') {
        System.err.println("PBS: Job " + jobId + " was not running");
        return -1;
    }

    int[] ports;
    if (cmd.hasOption('h')) {
        hosts = cmd.getOptionValues('h');
        ports = new int[hosts.length];
        String[] tmpH = d.getHostnames();
        int[] tmpP = d.getPorts();
        TObjectIntHashMap<String> host2port = new TObjectIntHashMap<String>(tmpH.length);
        for (int i = 0; i < tmpH.length; i++) {
            host2port.put(tmpH[i], tmpP[i]);
        }
        int i = 0;
        for (String h : hosts) {
            if (!host2port.contains(h)) {
                throw new IllegalArgumentException("Host " + h + " is not a member of this distributed job");
            }
            ports[i++] = host2port.get(h);
        }

    } else {
        hosts = d.getHostnames();
        ports = d.getPorts();
    }

    final String secret = d.getSecret();
    if (secret == null)
        throw new IllegalArgumentException(
                "No secret found - pbsdsh called too early? " + Arrays.toString(d.getHostnames()));

    LOG.debug("To run on " + Arrays.toString(hosts));
    final CyclicBarrier barrier = new CyclicBarrier(1 + hosts.length);
    int i = 0;
    for (final String h : hosts) {
        final int port = ports[i++];
        new Thread() {
            @Override
            public void run() {
                try {
                    if (connectToSister(h, port, secret, dibcommand) != 0)
                        LOG.error("Could not connect");
                } catch (Exception e) {
                    LOG.error("Could not connect", e);
                } finally {
                    try {
                        barrier.await();
                    } catch (Exception e) {
                        LOG.error("Barrier problem?");
                    }
                }
            }
        }.start();
    }
    barrier.await();
    return 0;
}

From source file:org.jolokia.client.request.J4pReadIntegrationTest.java

@Test
public void error404ConnectionTest() throws Exception {
    final J4pReadRequest req = new J4pReadRequest(itSetup.getAttributeMBean(), "LongSeconds");
    try {/* ww w. j  a  va2  s.c  o  m*/
        stop();
        startWithoutAgent();
        j4pClient.execute(req);
        fail();
    } catch (J4pRemoteException exp) {
        assertEquals(404, exp.getStatus());
    }
    stop();
    start();

    final CyclicBarrier barrier = new CyclicBarrier(10);
    final Queue errors = new ConcurrentLinkedQueue();
    Runnable run = new Runnable() {
        public void run() {
            try {
                j4pClient.execute(req);
            } catch (Exception e) {
                errors.add(1);
                System.err.println(e);
            }
            try {
                barrier.await();
            } catch (InterruptedException ex) {
                return;
            } catch (BrokenBarrierException ex) {
                return;
            }
        }
    };

    for (int i = 0; i < 10; i++) {
        new Thread(run).start();
    }
    if (barrier.await() == 0) {
        //System.err.println("Finished");
        assertEquals(0, errors.size(), "Concurrent calls should work");
    }
}

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();
    Assert.assertTrue(list.contains("[ PERCEPTUALLY_SAME ] testName"));

    overallStatistics.onSuiteCompleted();
    barrier.await();//from  www.j a  v  a 2 s . co m
    Assert.assertTrue(list.contains("  Overall Statistics:"));
    Assert.assertTrue(list.contains("  PERCEPTUALLY_SAME: 1"));
}

From source file:com.esminis.server.library.service.server.installpackage.InstallerPackage.java

private void stopServer(Context context, ServerControl serverControl) {
    final CyclicBarrier barrier = new CyclicBarrier(2);
    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override/*  w  w  w . ja va2 s  . com*/
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == null
                    || !intent.getAction().equals(MainActivity.getIntentActionServerStatus(context))) {
                return;
            }
            final Bundle extras = intent.getExtras();
            if (extras == null || extras.containsKey("errorLine") || extras.getBoolean("running")) {
                return;
            }
            try {
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException ignored) {
            }
        }
    };
    context.registerReceiver(receiver, new IntentFilter(MainActivity.getIntentActionServerStatus(context)));
    preferences.set(context, Preferences.SERVER_STARTED, false);
    serverControl.requestStop(null);
    try {
        barrier.await();
    } catch (InterruptedException | BrokenBarrierException ignored) {
    }
    context.unregisterReceiver(receiver);
}