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:Main.java

public static void main(String[] args) {
    CyclicBarrier barrier = new CyclicBarrier(2);
    new Thread() {
        @Override//from  w  w 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 await(CyclicBarrier barrier) {
    try {/*  w  w w .  ja v a2 s . c  o  m*/
        barrier.await();
    } catch (Exception e) {
        throw new Error(e);
    }
}

From source file:org.scribble.cli.ExecUtil.java

/**
 * Waits for a process to terminate.//from w  ww. ja v a 2s .  c o m
 * 
 * @param process The process it should wait for.
 * @param onStart Notifies others upon starting.
 * @return The return code.
 */
public static Callable<Integer> waitFor(final Process process, final CyclicBarrier onStart) {
    return new Callable<Integer>() {
        public Integer call() throws InterruptedException, BrokenBarrierException {
            onStart.await();
            return process.waitFor();
        }
    };
}

From source file:org.scribble.cli.ExecUtil.java

/**
 * Converts an input stream to a string as much as possible. It stops
 * at IOExceptions, but returns what it read thus far.
 * @param in The input stream.//from w w  w .ja va 2  s  . c om
 * @param onStart Notify others that it started. 
 */
private static Callable<String> toString(final InputStream input, final CyclicBarrier onStart) {
    return new Callable<String>() {
        public String call() throws InterruptedException, BrokenBarrierException, IOException {
            onStart.await();
            try {
                return IOUtils.toString(input);
            } finally {
                IOUtils.closeQuietly(input);
            }
        }
    };
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * Reads a file./*from   w  ww . j a v  a  2s.  c o m*/
 *
 * @param count the count to determine the filename
 * @throws Exception if it fails to read
 */
private static void readFile(CyclicBarrier barrier, AtomicLong runTime, int count) throws Exception {
    FileSystem fileSystem = FileSystem.Factory.get();
    byte[] buffer = new byte[(int) Math.min(sFileSize, 4 * Constants.MB)];

    barrier.await();
    long startTime = System.nanoTime();
    try (FileInStream inStream = fileSystem.openFile(filename(count))) {
        while (inStream.read(buffer) != -1) {
        }
    }
    runTime.addAndGet(System.nanoTime() - startTime);
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * Writes a file.//from w  w  w  .  ja va 2 s . co  m
 *
 * @param count the count to determine the filename
 * @throws Exception if it fails to write
 */
private static void writeFile(CyclicBarrier barrier, AtomicLong runtime, int count) throws Exception {
    FileSystem fileSystem = FileSystem.Factory.get();
    byte[] buffer = new byte[(int) Math.min(sFileSize, 4 * Constants.MB)];
    Arrays.fill(buffer, (byte) 'a');
    AlluxioURI path = filename(count);

    if (fileSystem.exists(path)) {
        fileSystem.delete(path);
    }

    barrier.await();
    long startTime = System.nanoTime();
    long bytesWritten = 0;
    try (FileOutStream outStream = fileSystem.createFile(path)) {
        while (bytesWritten < sFileSize) {
            outStream.write(buffer, 0, (int) Math.min(buffer.length, sFileSize - bytesWritten));
            bytesWritten += buffer.length;
        }
    }
    runtime.addAndGet(System.nanoTime() - startTime);
}

From source file:jetbrains.exodus.gc.GarbageCollectorTestInMemory.java

@Test
public void testTextIndexLikeWithDeletionsAndConcurrentReading()
        throws InterruptedException, BrokenBarrierException {
    final long started = System.currentTimeMillis();
    prepare();//from   w w  w.  j  av a 2  s . co m
    final Transaction txn = env.beginTransaction();
    final Store store = env.openStore("store", getStoreConfig(false), txn);
    final Store storeDups = env.openStore("storeDups", getStoreConfig(true), txn);
    txn.commit();
    final Throwable[] throwable = { null };
    final JobProcessor[] processors = new JobProcessor[10];
    for (int i = 0; i < processors.length; ++i) {
        processors[i] = ThreadJobProcessorPool.getOrCreateJobProcessor("test processor" + i);
        processors[i].start();
    }
    final CyclicBarrier barrier = new CyclicBarrier(processors.length + 1);
    processors[0].queue(new Job() {
        @Override
        protected void execute() throws Throwable {
            barrier.await();
            try {
                while (System.currentTimeMillis() - started < TEST_DURATION) {
                    env.executeInTransaction(new TransactionalExecutable() {
                        @Override
                        public void execute(@NotNull final Transaction txn) {
                            int randomInt = rnd.nextInt() & 0x3fffffff;
                            final int count = 4 + (randomInt) & 0x1f;
                            for (int j = 0; j < count; randomInt += ++j) {
                                final int intKey = randomInt & 0x3fff;
                                final ArrayByteIterable key = IntegerBinding.intToCompressedEntry(intKey);
                                final int valueLength = 50 + (randomInt % 100);
                                store.put(txn, key, new ArrayByteIterable(new byte[valueLength]));
                                storeDups.put(txn, key, IntegerBinding.intToEntry(randomInt % 32));
                            }
                            randomInt = (randomInt * randomInt) & 0x3fffffff;
                            for (int j = 0; j < count; randomInt += ++j) {
                                final int intKey = randomInt & 0x3fff;
                                final ArrayByteIterable key = IntegerBinding.intToCompressedEntry(intKey);
                                store.delete(txn, key);
                                try (Cursor cursor = storeDups.openCursor(txn)) {
                                    if (cursor.getSearchBoth(key, IntegerBinding.intToEntry(randomInt % 32))) {
                                        cursor.deleteCurrent();
                                    }
                                }
                            }
                        }
                    });
                    Thread.sleep(0);
                }
            } catch (Throwable t) {
                throwable[0] = t;
            }
        }
    });
    for (int i = 1; i < processors.length; ++i) {
        processors[i].queue(new Job() {
            @Override
            protected void execute() throws Throwable {
                try {
                    barrier.await();
                    while (System.currentTimeMillis() - started < TEST_DURATION) {
                        int randomInt = rnd.nextInt() & 0x3fffffff;
                        for (int j = 0; j < 100; randomInt += ++j) {
                            final int intKey = randomInt & 0x3fff;
                            final ArrayByteIterable key = IntegerBinding.intToCompressedEntry(intKey);
                            getAutoCommit(store, key);
                            getAutoCommit(storeDups, key);
                            Thread.sleep(0);
                        }
                        Thread.sleep(50);
                    }
                } catch (Throwable t) {
                    throwable[0] = t;
                }
            }
        });
    }
    barrier.await();
    for (final JobProcessor processor : processors) {
        processor.finish();
    }
    final Throwable t = throwable[0];
    if (t != null) {
        memory.dump(new File(System.getProperty("user.home"), "dump"));
        logging.error("User code exception: ", t);
        Assert.assertTrue(false);
    }
}

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

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

    final StopWatch sw = new StopWatch();

    final CyclicBarrier stopBarrier = new CyclicBarrier(11, new Runnable() {
        @Override/* w w w  . ja v a2s . c  om*/
        public void run() {
            sw.stop();
        }
    });

    sw.start();

    for (int i = 0; i < 10; ++i) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1L);
                    stopBarrier.await();
                } catch (Exception ex) {
                    throw new AssertionError(ex);
                }
            }
        };

        ScheduledFuture<?> future = execSrv.schedule(r, 0L, TimeUnit.NANOSECONDS);

        // compare with epsilon to make up for bad accuracy
        assertTrue(abs(future.getDelay(TimeUnit.MILLISECONDS)) < EPSILON);
    }

    stopBarrier.await();

    assertTrue(sw.getTime() < EPSILON);
}

From source file:hr.fer.zemris.vhdllab.platform.ui.command.DevFloodWithCompliationRequestsCommand.java

private void floodWithCompilationRequests(final Integer fileId, final String name) {
    String input = JOptionPane.showInputDialog("How many?", "30");
    int floodCount = Integer.parseInt(input);

    final List<String> results = Collections.synchronizedList(new ArrayList<String>(floodCount));
    final CyclicBarrier barrier = new CyclicBarrier(floodCount);
    List<Thread> threads = new ArrayList<Thread>(floodCount);
    long start = System.currentTimeMillis();
    for (int i = 0; i < floodCount; i++) {
        Thread thread = new Thread(new Runnable() {
            @SuppressWarnings("synthetic-access")
            @Override//w ww .ja v  a  2s. c om
            public void run() {
                try {
                    barrier.await();
                } catch (Exception e) {
                    throw new UnhandledException(e);
                }
                logger.info("sending at: " + System.currentTimeMillis());
                List<CompilationMessage> messages;
                try {
                    messages = simulator.compile(fileId);
                } catch (SimulatorTimeoutException e) {
                    String message = localizationSource.getMessage("simulator.compile.timout",
                            new Object[] { name });
                    messages = Collections.singletonList(new CompilationMessage(message));
                } catch (NoAvailableProcessException e) {
                    String message = localizationSource.getMessage("simulator.compile.no.processes",
                            new Object[] { name });
                    messages = Collections.singletonList(new CompilationMessage(message));
                }

                if (messages.isEmpty()) {
                    results.add("Successful");
                } else {
                    results.add(messages.get(0).getText());
                }
            }
        });
        thread.start();
        threads.add(thread);
    }

    logger.info("waiting for threads to complete...");
    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            throw new UnhandledException(e);
        }
    }
    long end = System.currentTimeMillis();
    logger.info("ended in " + (end - start) + " ms");
    showResults(results);
}

From source file:org.apache.hadoop.util.TestStringUtils.java

@Test
//Multithreaded Test GetFormattedTimeWithDiff()
public void testGetFormattedTimeWithDiff() throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(16);
    final CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
    for (int i = 0; i < 10; i++) {

        executorService.execute(new Runnable() {
            @Override/*w w  w. j av a2s .  c  om*/
            public void run() {
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    //Ignored
                }
                final long end = System.currentTimeMillis();
                final long start = end - 30000;
                String formattedTime1 = StringUtils.getFormattedTimeWithDiff(FAST_DATE_FORMAT, start, end);
                String formattedTime2 = StringUtils.getFormattedTimeWithDiff(FAST_DATE_FORMAT, start, end);
                assertTrue("Method returned inconsistent results indicative of" + " a race condition",
                        formattedTime1.equals(formattedTime2));

            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(50, TimeUnit.SECONDS);
}