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(long timeout, TimeUnit unit)
        throws InterruptedException, BrokenBarrierException, TimeoutException 

Source Link

Document

Waits until all #getParties parties have invoked await on this barrier, or the specified waiting time elapses.

Usage

From source file:com.adaptris.core.interceptor.ThrottlingInterceptor.java

private boolean throttle(final long delay) {
    final CyclicBarrier barrier = new CyclicBarrier(2);
    // This is to make sure we don't break the barrier before the real delay is up.
    // //www. ja  v  a2  s . com
    long barrierDelay = delay + TimeUnit.SECONDS.toMillis(1L);
    boolean result = true;
    try {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(delay);
                    barrier.await(TimeUnit.SECONDS.toMillis(1L), TimeUnit.MILLISECONDS);
                } catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
                    log.trace("Interrupted during sleep; breaking barrier");
                    barrier.reset();
                }
            }

        });
        barrier.await(barrierDelay, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
        result = false;
    }
    return result;
}

From source file:de.hybris.platform.test.HJMPOptimisticConcurrencyPerformanceTest.java

private void doTestMissingUpdateProblem() throws JaloBusinessException, InterruptedException {
    final Media m = MediaManager.getInstance().createMedia("codeBefore");
    try {//from  w  w  w .j  a  va2s.co m
        m.setMime("mimeBefore");
        m.setDescription("descriptionBefore");

        final CyclicBarrier txStartJoinPoint = new CyclicBarrier(2);
        final AtomicReference<Throwable> tx1Error = new AtomicReference<Throwable>();
        final AtomicReference<Throwable> tx2Error = new AtomicReference<Throwable>();

        final Thread[] threads = createTxThreads(//
                new TxRunnable() {
                    @Override
                    public void run() throws Exception {
                        txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to begin
                        assertEquals("codeBefore", m.getCode());
                        txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to have read same version
                        m.setMime("tx1Mime");
                        m.setCode("tx1Code");
                    }
                }, //
                new TxRunnable() {
                    @Override
                    public void run() throws Exception {
                        txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx
                        assertEquals("codeBefore", m.getCode());
                        txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to have read same version
                        m.setMime("tx2Mime");
                        m.setDescription("tx2Description");
                    }
                }, tx1Error, tx2Error);

        threads[0].start();
        threads[1].start();

        threads[0].join(50 * 1000);
        threads[1].join(50 * 1000);

        assertFalse(threads[0].isAlive());
        assertFalse(threads[1].isAlive());

        if (isConcurrentModificationCheckEnabled()) {
            assertEquals("missing update from tx1", "tx1Code", m.getCode());
            assertEquals("missing update from tx1", "tx1Mime", m.getMime());
            assertEquals("unexpected update from tx2", "descriptionBefore", m.getDescription());
            assertNull("unexpected error from tx1", tx1Error.get());
            assertNotNull("expected error from tx2", tx2Error.get());
        } else {
            assertNull("unexpected error from tx1", tx1Error.get());
            assertNull("unexpected error from tx2", tx2Error.get());
            assertEquals("missing update from tx1", "tx1Code", m.getCode());
            assertEquals("missing update from tx2", "tx2Description", m.getDescription());
            assertEquals("missing update from tx2", "tx2Mime", m.getMime());
        }
    } finally {
        m.remove();
    }
}

From source file:org.casbah.provider.openssl.OpenSslWrapper.java

public int executeCommand(InputStream input, OutputStream output, OutputStream error,
        final List<String> parameters) throws IOException, InterruptedException {
    List<String> fullParams = new ArrayList<String>(parameters);
    fullParams.add(0, opensslExecutable);
    ProcessBuilder processBuilder = new ProcessBuilder(fullParams);
    CyclicBarrier barrier = new CyclicBarrier(3);
    Map<String, String> env = processBuilder.environment();
    env.put(CASBAH_SSL_CA_ROOT, caRootDir.getAbsolutePath());
    Process proc = processBuilder.start();
    if (input != null) {
        BufferedOutputStream stdin = new BufferedOutputStream(proc.getOutputStream());
        IOUtils.copy(input, stdin);/* w  w w  .  jav  a2 s.  c  o m*/
        stdin.flush();
    }
    StreamConsumer outputConsumer = new StreamConsumer(output, proc.getInputStream(), barrier, TIMEOUT);
    StreamConsumer errorConsumer = new StreamConsumer(error, proc.getErrorStream(), barrier, TIMEOUT);
    outputConsumer.start();
    errorConsumer.start();
    int returnValue = proc.waitFor();
    try {
        barrier.await(TIMEOUT, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnValue;
}

From source file:com.adaptris.core.PoolingWorkflow.java

private void populatePool() throws CoreException {
    int size = minIdle();
    ExecutorService populator = Executors.newCachedThreadPool();
    try {//from   w ww  .j a va  2 s .c  om
        final CyclicBarrier barrier = new CyclicBarrier(size + 1);
        log.trace("Need more ({}) children as soon as possible to handle work. Get to it", size);
        final List<Worker> workers = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            populator.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Worker w = objectPool.borrowObject();
                        workers.add(w);
                        barrier.await(initWaitTimeMs(), TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        barrier.reset();
                    }
                }
            });
        }
        barrier.await(initWaitTimeMs(), TimeUnit.MILLISECONDS);
        for (Worker worker : workers) {
            objectPool.returnObject(worker);
        }
    } catch (Exception e) {
        throw new CoreException(e);
    } finally {
        populator.shutdownNow();
    }
}

From source file:de.hybris.platform.test.ThreadPoolTest.java

@Test
public void testTransactionCleanUpSimple()
        throws InterruptedException, BrokenBarrierException, TimeoutException {
    final boolean flagBefore = Config.getBoolean("transaction.monitor.begin", false);
    Config.setParameter("transaction.monitor.begin", "true");
    ThreadPool pool = null;/*from   w w w.j  av a 2s. c  o  m*/
    try {
        pool = new ThreadPool(Registry.getCurrentTenantNoFallback().getTenantID(), 1);

        final GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = 1;
        config.maxIdle = 1;
        config.maxWait = -1;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.timeBetweenEvictionRunsMillis = 30 * 1000; // keep idle threads for at most 30 sec
        pool.setConfig(config);

        final CyclicBarrier gate = new CyclicBarrier(2);
        final AtomicReference<Throwable> threadError = new AtomicReference<Throwable>();
        final AtomicReference<RecordingTransaction> threadTransaction = new AtomicReference<ThreadPoolTest.RecordingTransaction>();
        final PoolableThread thread1 = pool.borrowThread();
        thread1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final Transaction tx = new RecordingTransaction();
                    tx.activateAsCurrentTransaction();
                    tx.begin();
                    tx.begin(); // second time
                    tx.begin(); // third time
                    assertTrue(tx.isRunning());
                    assertEquals(3, tx.getOpenTransactionCount());
                    threadTransaction.set((RecordingTransaction) tx);
                    gate.await(10, TimeUnit.SECONDS);
                } catch (final Throwable t) {
                    threadError.set(t);
                }
            }
        });
        gate.await(10, TimeUnit.SECONDS);
        assertNull(threadError.get());
        // busy waiting for correct number of rollbacks - at the moment there is no hook for a better solution
        final RecordingTransaction tx = threadTransaction.get();
        final long maxWait = System.currentTimeMillis() + (15 * 1000);
        while (tx.rollbackCounter.get() < 3 && System.currentTimeMillis() < maxWait) {
            Thread.sleep(100);
        }
        assertEquals(3, tx.rollbackCounter.get());

        final PoolableThread thread2 = pool.borrowThread();
        assertNotSame(thread1, thread2);
    } finally {
        if (pool != null) {
            try {
                pool.close();
            } catch (final Exception e) {
                // can't help it
            }
        }
        Config.setParameter("transaction.monitor.begin", BooleanUtils.toStringTrueFalse(flagBefore));
    }
}

From source file:org.apache.hadoop.yarn.server.nodemanager.TestNodeStatusUpdater.java

@Test(timeout = 200000)
public void testNodeStatusUpdaterRetryAndNMShutdown() throws Exception {
    final long connectionWaitSecs = 1000;
    final long connectionRetryIntervalMs = 1000;
    int port = ServerSocketUtil.getPort(49156, 10);
    YarnConfiguration conf = createNMConfig(port);
    conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_MS, connectionWaitSecs);
    conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_MS, connectionRetryIntervalMs);
    conf.setLong(YarnConfiguration.NM_SLEEP_DELAY_BEFORE_SIGKILL_MS, 5000);
    conf.setLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 1);
    CyclicBarrier syncBarrier = new CyclicBarrier(2);
    nm = new MyNodeManager2(syncBarrier, conf);
    nm.init(conf);//from  w ww  . j a  v  a2s .com
    nm.start();
    // start a container
    ContainerId cId = TestNodeManagerShutdown.createContainerId();
    FileContext localFS = FileContext.getLocalFSFileContext();
    TestNodeManagerShutdown.startContainer(nm, cId, localFS, nmLocalDir, new File("start_file.txt"), port);

    try {
        // Wait until we start stopping
        syncBarrier.await(10000, TimeUnit.MILLISECONDS);
        // Wait until we finish stopping
        syncBarrier.await(10000, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
    }
    Assert.assertFalse("Containers not cleaned up when NM stopped", assertionFailedInThread.get());
    Assert.assertTrue(((MyNodeManager2) nm).isStopped);
    Assert.assertTrue("calculate heartBeatCount based on" + " connectionWaitSecs and RetryIntervalSecs",
            heartBeatID == 2);
}