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:org.apache.struts2.EmbeddedJSPResultTest.java

public void testCacheInstanceWithManyThreads() throws BrokenBarrierException, InterruptedException {
    //start a bunch of thread at the same time using CyclicBarrier and hit the cache
    //then wait for all the threads to end and check that they all got a reference to the same object
    //and the cache size should be 1

    DummyServletCache cache = new DummyServletCache();
    int numThreads = 70;

    CyclicBarrier startBarrier = new CyclicBarrier(numThreads + 1);
    CyclicBarrier endBarrier = new CyclicBarrier(numThreads + 1);

    List<ServletGetRunnable> runnables = new ArrayList<ServletGetRunnable>(numThreads);

    //create the threads
    for (int i = 0; i < numThreads; i++) {
        ServletGetRunnable runnable = new ServletGetRunnable(cache, startBarrier, endBarrier,
                ActionContext.getContext());
        Thread thread = new Thread(runnable);
        runnables.add(runnable);//from w  ww . j a  va2s . c o  m
        thread.start();
    }

    startBarrier.await();
    endBarrier.await();
    Object servlet = cache.get("org/apache/struts2/simple0.jsp");
    assertEquals(1, cache.size());

    for (ServletGetRunnable runnable : runnables) {
        assertSame(servlet, runnable.getObject());
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldEvalInMultipleThreads() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();

    final CyclicBarrier barrier = new CyclicBarrier(2);
    final AtomicInteger i1 = new AtomicInteger(0);
    final AtomicBoolean b1 = new AtomicBoolean(false);
    final Thread t1 = new Thread(() -> {
        try {//from   ww w . j a  v  a 2  s .  co m
            barrier.await();
            i1.set((Integer) gremlinExecutor.eval("1+1").get());
        } catch (Exception ex) {
            b1.set(true);
        }
    });

    final AtomicInteger i2 = new AtomicInteger(0);
    final AtomicBoolean b2 = new AtomicBoolean(false);
    final Thread t2 = new Thread(() -> {
        try {
            barrier.await();
            i2.set((Integer) gremlinExecutor.eval("1+1").get());
        } catch (Exception ex) {
            b2.set(true);
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    assertEquals(2, i1.get());
    assertEquals(2, i2.get());
    assertFalse(b1.get());
    assertFalse(b2.get());

    gremlinExecutor.close();
}

From source file:ch.cyberduck.core.PathTest.java

@Test
public void testTransferInterrupt() throws Exception {
    final Path p = new NullPath("/t", Path.FILE_TYPE);
    final TransferStatus status = new TransferStatus();
    final CyclicBarrier lock = new CyclicBarrier(2);
    final CyclicBarrier exit = new CyclicBarrier(2);
    status.setLength(432768L);//from  w w w. java  2  s  .co  m
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                p.transfer(new NullInputStream(status.getLength()), new NullOutputStream(),
                        new StreamListener() {
                            @Override
                            public void bytesSent(long bytes) {
                                //
                            }

                            @Override
                            public void bytesReceived(long bytes) {
                                try {
                                    lock.await();
                                    exit.await();
                                } catch (InterruptedException e) {
                                    fail(e.getMessage());
                                } catch (BrokenBarrierException e) {
                                    fail(e.getMessage());
                                }
                            }
                        }, -1, status);
            } catch (IOException e) {
                assertTrue(e instanceof ConnectionCanceledException);
            }
        }
    }).start();
    lock.await();
    status.setCanceled();
    exit.await();
    assertFalse(status.isComplete());
    assertTrue(status.isCanceled());
    assertEquals(32768L, status.getCurrent());
}

From source file:org.apache.bookkeeper.metadata.etcd.EtcdRegistrationTest.java

private void testConcurrentRegistration(boolean readonly) throws Exception {
    final String bookieId;
    if (readonly) {
        bookieId = runtime.getMethodName() + "-readonly:3181";
    } else {//  w ww  .j  a v a 2  s. co m
        bookieId = runtime.getMethodName() + ":3181";
    }
    final int numBookies = 10;
    @Cleanup("shutdown")
    ExecutorService executor = Executors.newFixedThreadPool(numBookies);
    final CyclicBarrier startBarrier = new CyclicBarrier(numBookies);
    final CyclicBarrier completeBarrier = new CyclicBarrier(numBookies);
    final CompletableFuture<Void> doneFuture = new CompletableFuture<>();
    final AtomicInteger numSuccesses = new AtomicInteger(0);
    final AtomicInteger numFailures = new AtomicInteger(0);
    for (int i = 0; i < numBookies; i++) {
        executor.submit(() -> {
            try (EtcdRegistrationManager regMgr = new EtcdRegistrationManager(newEtcdClient(), scope, 1)) {
                try {
                    startBarrier.await();
                    regMgr.registerBookie(bookieId, readonly);
                    numSuccesses.incrementAndGet();
                } catch (InterruptedException e) {
                    log.warn("Interrupted at waiting for the other threads to start", e);
                } catch (BrokenBarrierException e) {
                    log.warn("Start barrier is broken", e);
                } catch (BookieException e) {
                    numFailures.incrementAndGet();
                }
                try {
                    completeBarrier.await();
                } catch (InterruptedException e) {
                    log.warn("Interrupted at waiting for the other threads to complete", e);
                } catch (BrokenBarrierException e) {
                    log.warn("Complete barrier is broken", e);
                }
                FutureUtils.complete(doneFuture, null);
            }
        });
    }
    doneFuture.join();
    assertEquals(1, numSuccesses.get());
    assertEquals(numBookies - 1, numFailures.get());
}

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

/**
 * Verify that setting selfPopulating=true will guarantee only 1 invocation
 * of the cached method.//from  ww  w  . j a  v  a 2  s  .  co m
 * 
 * @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:org.apache.hadoop.hdfs.server.datanode.TestDataNodeHotSwapVolumes.java

/**
 * Test the case that remove a data volume on a particular DataNode when the
 * volume is actively being written.// w  w  w  .ja va 2s. com
 * @param dataNodeIdx the index of the DataNode to remove a volume.
 */
private void testRemoveVolumeBeingWrittenForDatanode(int dataNodeIdx) throws IOException,
        ReconfigurationException, TimeoutException, InterruptedException, BrokenBarrierException {
    // Starts DFS cluster with 3 DataNodes to form a pipeline.
    startDFSCluster(1, 3);

    final short REPLICATION = 3;
    final DataNode dn = cluster.getDataNodes().get(dataNodeIdx);
    final FileSystem fs = cluster.getFileSystem();
    final Path testFile = new Path("/test");
    final long lastTimeDiskErrorCheck = dn.getLastDiskErrorCheck();

    FSDataOutputStream out = fs.create(testFile, REPLICATION);

    Random rb = new Random(0);
    byte[] writeBuf = new byte[BLOCK_SIZE / 2]; // half of the block.
    rb.nextBytes(writeBuf);
    out.write(writeBuf);
    out.hflush();

    // Make FsDatasetSpi#finalizeBlock a time-consuming operation. So if the
    // BlockReceiver releases volume reference before finalizeBlock(), the blocks
    // on the volume will be removed, and finalizeBlock() throws IOE.
    final FsDatasetSpi<? extends FsVolumeSpi> data = dn.data;
    dn.data = Mockito.spy(data);
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws IOException, InterruptedException {
            Thread.sleep(1000);
            // Bypass the argument to FsDatasetImpl#finalizeBlock to verify that
            // the block is not removed, since the volume reference should not
            // be released at this point.
            data.finalizeBlock((ExtendedBlock) invocation.getArguments()[0]);
            return null;
        }
    }).when(dn.data).finalizeBlock(any(ExtendedBlock.class));

    final CyclicBarrier barrier = new CyclicBarrier(2);

    List<String> oldDirs = getDataDirs(dn);
    final String newDirs = oldDirs.get(1); // Remove the first volume.
    final List<Exception> exceptions = new ArrayList<>();
    Thread reconfigThread = new Thread() {
        public void run() {
            try {
                barrier.await();
                dn.reconfigurePropertyImpl(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, newDirs);
            } catch (ReconfigurationException | InterruptedException | BrokenBarrierException e) {
                exceptions.add(e);
            }
        }
    };
    reconfigThread.start();

    barrier.await();
    rb.nextBytes(writeBuf);
    out.write(writeBuf);
    out.hflush();
    out.close();

    reconfigThread.join();

    // Verify the file has sufficient replications.
    DFSTestUtil.waitReplication(fs, testFile, REPLICATION);
    // Read the content back
    byte[] content = DFSTestUtil.readFileBuffer(fs, testFile);
    assertEquals(BLOCK_SIZE, content.length);

    // If an IOException thrown from BlockReceiver#run, it triggers
    // DataNode#checkDiskError(). So we can test whether checkDiskError() is called,
    // to see whether there is IOException in BlockReceiver#run().
    assertEquals(lastTimeDiskErrorCheck, dn.getLastDiskErrorCheck());

    if (!exceptions.isEmpty()) {
        throw new IOException(exceptions.get(0).getCause());
    }
}

From source file:org.acmsl.queryj.api.AbstractTemplateGeneratorThread.java

/**
 * Runs the template generation process.
 * @param templateGenerator the template generator.
 * @param template the template.// www  .  j  a v a 2s .  c  o  m
 * @param outputDir the output folder.
 * @param rootFolder the root folder.
 * @param charset the {@link Charset} to use.
 * @param threadIndex the thread index.
 * @param barrier the cyclic barrier.
 * @param log the {@link Log} instance.
 */
@ThreadSafe
protected void runGenerator(@NotNull final TG templateGenerator, @NotNull final T template,
        @NotNull final File outputDir, @NotNull final File rootFolder, @NotNull final Charset charset,
        final int threadIndex, @Nullable final CyclicBarrier barrier, @Nullable final Log log) {
    boolean generated = false;

    try {
        generated = templateGenerator.write(template, outputDir, rootFolder, charset);
    } catch (@NotNull final QueryJBuildException unknownException) {
        if (log != null) {
            log.warn(unknownException);
        }
    } catch (@NotNull final IOException ioException) {
        if (log != null) {
            log.warn(ioException);
        }
    }

    if (generated) {
        if (log != null) {
            log.debug(buildSuccessLogMessage(template, threadIndex));
        }
    }

    if (barrier != null) {
        try {
            barrier.await();
        } catch (@NotNull final InterruptedException interrupted) {
            if (log != null) {
                log.debug("Interrupted thread", interrupted);
            }

            Thread.currentThread().interrupt();
        } catch (@NotNull final BrokenBarrierException brokenBarrier) {
            if (log != null) {
                log.warn(AbstractTemplateWritingHandler.BROKEN_BARRIER_LITERAL, brokenBarrier);
            }
        }
    }
}

From source file:org.apache.flume.channel.kafka.TestKafkaChannel.java

private List<Event> pullEvents(final KafkaChannel channel, ExecutorCompletionService<Void> submitterSvc,
        final int total, final boolean testRollbacks, final boolean retryAfterRollback) {
    final List<Event> eventsPulled = Collections.synchronizedList(new ArrayList<Event>(50));
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicInteger rolledBackCount = new AtomicInteger(0);
    final AtomicBoolean startedGettingEvents = new AtomicBoolean(false);
    final AtomicBoolean rolledBack = new AtomicBoolean(false);
    for (int k = 0; k < 5; k++) {
        final int index = k;
        submitterSvc.submit(new Callable<Void>() {
            @Override//from  w ww. j  a va2s .com
            public Void call() throws Exception {
                Transaction tx = null;
                final List<Event> eventsLocal = Lists.newLinkedList();
                int takenByThisThread = 0;
                channel.registerThread();
                Thread.sleep(1000);
                barrier.await();
                while (counter.get() < (total - rolledBackCount.get())) {
                    if (tx == null) {
                        tx = channel.getTransaction();
                        tx.begin();
                    }
                    try {
                        Event e = channel.take();
                        if (e != null) {
                            startedGettingEvents.set(true);
                            eventsLocal.add(e);
                        } else {
                            if (testRollbacks && index == 4 && (!rolledBack.get())
                                    && startedGettingEvents.get()) {
                                tx.rollback();
                                tx.close();
                                tx = null;
                                rolledBack.set(true);
                                final int eventsLocalSize = eventsLocal.size();
                                eventsLocal.clear();
                                if (!retryAfterRollback) {
                                    rolledBackCount.set(eventsLocalSize);
                                    return null;
                                }
                            } else {
                                tx.commit();
                                tx.close();
                                tx = null;
                                eventsPulled.addAll(eventsLocal);
                                counter.getAndAdd(eventsLocal.size());
                                eventsLocal.clear();
                            }
                        }
                    } catch (Exception ex) {
                        eventsLocal.clear();
                        if (tx != null) {
                            tx.rollback();
                            tx.close();
                        }
                        tx = null;
                        ex.printStackTrace();
                    }
                }
                // Close txn.
                return null;
            }
        });
    }
    return eventsPulled;
}

From source file:org.apache.hadoop.contrib.bkjournal.TestBookKeeperJournalManager.java

/**
 * Tests that concurrent calls to format will still allow one to succeed.
 *///from  w w  w  .ja v  a2  s  .c o  m
@Test
public void testConcurrentFormat() throws Exception {
    final URI uri = BKJMUtil.createJournalURI("/hdfsjournal-concurrentformat");
    final NamespaceInfo nsi = newNSInfo();

    // populate with data first
    BookKeeperJournalManager bkjm = new BookKeeperJournalManager(conf, uri, nsi);
    bkjm.format(nsi);
    for (int i = 1; i < 100 * 2; i += 2) {
        bkjm.startLogSegment(i, NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);
        bkjm.finalizeLogSegment(i, i + 1);
    }
    bkjm.close();

    final int numThreads = 40;
    List<Callable<ThreadStatus>> threads = new ArrayList<Callable<ThreadStatus>>();
    final CyclicBarrier barrier = new CyclicBarrier(numThreads);

    for (int i = 0; i < numThreads; i++) {
        threads.add(new Callable<ThreadStatus>() {
            public ThreadStatus call() {
                BookKeeperJournalManager bkjm = null;
                try {
                    bkjm = new BookKeeperJournalManager(conf, uri, nsi);
                    barrier.await();
                    bkjm.format(nsi);
                    return ThreadStatus.COMPLETED;
                } catch (IOException ioe) {
                    LOG.info("Exception formatting ", ioe);
                    return ThreadStatus.GOODEXCEPTION;
                } catch (InterruptedException ie) {
                    LOG.error("Interrupted. Something is broken", ie);
                    Thread.currentThread().interrupt();
                    return ThreadStatus.BADEXCEPTION;
                } catch (Exception e) {
                    LOG.error("Some other bad exception", e);
                    return ThreadStatus.BADEXCEPTION;
                } finally {
                    if (bkjm != null) {
                        try {
                            bkjm.close();
                        } catch (IOException ioe) {
                            LOG.error("Error closing journal manager", ioe);
                        }
                    }
                }
            }
        });
    }
    ExecutorService service = Executors.newFixedThreadPool(numThreads);
    List<Future<ThreadStatus>> statuses = service.invokeAll(threads, 60, TimeUnit.SECONDS);
    int numCompleted = 0;
    for (Future<ThreadStatus> s : statuses) {
        assertTrue(s.isDone());
        assertTrue("Thread threw invalid exception",
                s.get() == ThreadStatus.COMPLETED || s.get() == ThreadStatus.GOODEXCEPTION);
        if (s.get() == ThreadStatus.COMPLETED) {
            numCompleted++;
        }
    }
    LOG.info("Completed " + numCompleted + " formats");
    assertTrue("No thread managed to complete formatting", numCompleted > 0);
}

From source file:org.openmrs.module.emrapi.adt.AdtServiceComponentTest.java

@Test
public void integrationTest_ADT_workflow_duplicate_visits() throws Exception {
    final Integer numberOfThreads = 5;
    final CyclicBarrier threadsBarrier = new CyclicBarrier(numberOfThreads);

    Callable<Integer> checkInCall = new Callable<Integer>() {

        @Override/*from   w  ww  .  jav  a 2  s. com*/
        public Integer call() throws Exception {
            Context.openSession();
            authenticate();
            try {
                LocationService locationService = Context.getLocationService();

                Patient patient = Context.getPatientService().getPatient(7);

                // parent location should support visits
                LocationTag supportsVisits = new LocationTag();
                supportsVisits.setName(EmrApiConstants.LOCATION_TAG_SUPPORTS_VISITS);
                locationService.saveLocationTag(supportsVisits);

                Location parentLocation = locationService.getLocation(2);
                parentLocation.addTag(supportsVisits);
                locationService.saveLocation(parentLocation);

                threadsBarrier.await();

                Encounter checkInEncounter = service.checkInPatient(patient, parentLocation, null, null, null,
                        false);

                return checkInEncounter.getVisit().getVisitId();
            } finally {
                Context.closeSession();
            }
        }
    };

    List<Callable<Integer>> checkInCalls = new ArrayList<Callable<Integer>>();
    for (int i = 0; i < numberOfThreads; i++) {
        checkInCalls.add(checkInCall);
    }

    ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

    List<Future<Integer>> checkIns = executorService.invokeAll(checkInCalls);

    Integer visitId = null;
    for (Future<Integer> checkIn : checkIns) {
        Integer nextVisitId = checkIn.get();
        if (visitId != null) {
            assertThat(nextVisitId, is(visitId));
        } else {
            visitId = nextVisitId;
        }
    }
}