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: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 w w  .  ja  va  2s .  c om*/
        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:com.tc.objectserver.impl.ObjectRequestManagerTest.java

public void testMultipleRequestObjects() {
    final TestObjectManager objectManager = new TestObjectManager(persistor.getManagedObjectPersistor());
    final TestDSOChannelManager channelManager = new TestDSOChannelManager();
    final TestClientStateManager clientStateManager = new TestClientStateManager();
    final TestSink requestSink = new TestSink();
    final TestSink respondSink = new TestSink();
    final ObjectRequestManagerImpl objectRequestManager = new ObjectRequestManagerImpl(objectManager,
            channelManager, clientStateManager, requestSink, respondSink, new ObjectStatsRecorder());

    final int objectsToBeRequested = 47;
    int numberOfRequestsMade = objectsToBeRequested / ObjectRequestManagerImpl.SPLIT_SIZE;
    if (objectsToBeRequested % ObjectRequestManagerImpl.SPLIT_SIZE > 0) {
        numberOfRequestsMade++;//from w ww  .j  a v  a 2s  . c o  m
    }
    final ObjectIDSet ids = createObjectIDSet(objectsToBeRequested);

    final List<ObjectRequestThread> objectRequestThreadList = new ArrayList<ObjectRequestThread>();
    final int numberOfRequestThreads = 10;
    final CyclicBarrier requestBarrier = new CyclicBarrier(numberOfRequestThreads);

    for (int i = 0; i < numberOfRequestThreads; i++) {
        final ClientID clientID = new ClientID(i);
        final ObjectRequestThread objectRequestThread = new ObjectRequestThread(requestBarrier,
                objectRequestManager, clientID, new ObjectRequestID(i), ids, LOOKUP_STATE.CLIENT);
        objectRequestThreadList.add(objectRequestThread);
    }

    // let's now start until all the request threads
    for (final ObjectRequestThread thread : objectRequestThreadList) {
        thread.start();
    }

    // now wait for all the threads
    for (final ObjectRequestThread thread : objectRequestThreadList) {
        try {
            thread.join();
        } catch (final InterruptedException e) {
            throw new AssertionError(e);
        }
    }

    // assert that there is only one request in the sink.
    assertEquals(respondSink.size(), numberOfRequestsMade);

    RespondToObjectRequestContext respondToObjectRequestContext;

    final int numOfResponses = respondSink.size();
    assertEquals(numOfResponses, numberOfRequestsMade);

    int numOfRequestedObjects = 0;
    int numOfRespondedObjects = 0;
    for (int i = 0; i < numOfResponses; i++) {
        try {
            respondToObjectRequestContext = (RespondToObjectRequestContext) respondSink.take();
        } catch (final InterruptedException e) {
            throw new AssertionError(e);
        }
        System.out.println("respond: " + respondToObjectRequestContext);

        assertNotNull(respondToObjectRequestContext);
        numOfRespondedObjects += respondToObjectRequestContext.getObjs().size();
        numOfRequestedObjects += respondToObjectRequestContext.getRequestedObjectIDs().size();
        assertEquals(false, respondToObjectRequestContext.getLookupState().isServerInitiated());
        assertEquals(0, respondToObjectRequestContext.getMissingObjectIDs().size());
    }
    assertEquals(objectsToBeRequested, numOfRequestedObjects);
    assertEquals(objectsToBeRequested, numOfRespondedObjects);

}

From source file:lockstep.LockstepServer.java

/**
 * This method puts the server in waiting for client connections. It returns
 * when the expected number of clients have successfully completed the 
 * handshake.//from  w  w w . j  a  v a2s . c  o  m
 * Parallel threads are started to handle the handshakes.
 * In case of failure, all threads are interrupted and then the exception is
 * propagated.
 * 
 * @throws IOException In case of failure on opening the ServerSocket and 
 * accepting connections through it 
 * @throws InterruptedException In case of failure during the handshake 
 * sessions
 */
private void handshakePhase() throws IOException, InterruptedException {
    ServerSocket tcpServerSocket = new ServerSocket(tcpPort);

    CyclicBarrier barrier = new CyclicBarrier(this.clientsNumber);
    CountDownLatch latch = new CountDownLatch(this.clientsNumber);

    //Each session of the protocol starts with a different random frame number
    int firstFrameNumber = (new Random()).nextInt(1000) + 100;

    Thread[] handshakeSessions = new Thread[clientsNumber];

    for (int i = 0; i < clientsNumber; i++) {
        Socket tcpConnectionSocket = tcpServerSocket.accept();
        LOG.info("Connection " + i + " accepted from " + tcpConnectionSocket.getInetAddress().getHostAddress());
        handshakeSessions[i] = new Thread(
                () -> serverHandshakeProtocol(tcpConnectionSocket, firstFrameNumber, barrier, latch, this));
        handshakeSessions[i].start();
    }
    try {
        latch.await();
    } catch (InterruptedException inEx) {
        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.interrupt();

        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.join();

        throw new InterruptedException();
    }
    LOG.info("All handshakes completed");
}

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/*from ww w.  ja  va  2  s.c o 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: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
        public Integer call() throws Exception {
            Context.openSession();
            authenticate();//from  w w  w. j  av a  2 s  .co  m
            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;
        }
    }
}

From source file:org.openehealth.ipf.commons.lbs.store.LargeBinaryStoreTest.java

@Test
public void testThreadSafety() throws Exception {
    final int NUM_THREADS = 4;
    final int ITERATIONS = 100;

    final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS);
    StoreTestThread[] threads = new StoreTestThread[NUM_THREADS];
    for (int idx = 0; idx < NUM_THREADS; ++idx) {
        threads[idx] = new StoreTestThread(barrier, ITERATIONS);
        threads[idx].start();/*from www  .j  a va 2 s .  com*/
    }

    for (int idx = 0; idx < NUM_THREADS; ++idx) {
        threads[idx].join();
        if (threads[idx].isFailed()) {
            throw threads[idx].getException();
        }
    }
}

From source file:org.sonar.core.persistence.SemaphoreDaoTest.java

@Test
public void test_concurrent_locks() throws Exception {
    for (int tests = 0; tests < 5; tests++) {
        dao.release("my-lock");
        int size = 5;
        CyclicBarrier barrier = new CyclicBarrier(size);
        CountDownLatch latch = new CountDownLatch(size);

        AtomicInteger locks = new AtomicInteger(0);
        for (int i = 0; i < size; i++) {
            new Runner(dao, locks, barrier, latch).start();
        }/*from  w  ww . java2s  .  c  o m*/
        latch.await();

        // semaphore was locked only 1 time
        assertThat(locks.get()).isEqualTo(1);
    }
}

From source file:org.apache.hadoop.mapreduce.v2.app.job.impl.TestJobImpl.java

@Test(timeout = 20000)
public void testCommitJobFailsJob() throws Exception {
    Configuration conf = new Configuration();
    conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir);
    AsyncDispatcher dispatcher = new AsyncDispatcher();
    dispatcher.init(conf);//w  w  w  .j  av a 2  s .com
    dispatcher.start();
    CyclicBarrier syncBarrier = new CyclicBarrier(2);
    OutputCommitter committer = new TestingOutputCommitter(syncBarrier, false);
    CommitterEventHandler commitHandler = createCommitterEventHandler(dispatcher, committer);
    commitHandler.init(conf);
    commitHandler.start();

    JobImpl job = createRunningStubbedJob(conf, dispatcher, 2, null);
    completeJobTasks(job);
    assertJobState(job, JobStateInternal.COMMITTING);

    // let the committer fail and verify the job fails
    syncBarrier.await();
    assertJobState(job, JobStateInternal.FAILED);
    dispatcher.stop();
    commitHandler.stop();
}

From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImplIT.java

@Test
public void testSummaryMultiThreadDedup() throws ZepException, InterruptedException, ExecutionException {
    // Attempts to create the same event from multiple threads - verifies we get the appropriate de-duping behavior
    // for the count and that we are holding the lock on the database appropriately.
    int poolSize = 10;
    final CyclicBarrier barrier = new CyclicBarrier(poolSize);
    ExecutorService executorService = Executors.newFixedThreadPool(poolSize);
    ExecutorCompletionService<String> ecs = new ExecutorCompletionService<String>(executorService);
    final Event event = EventTestUtils.createSampleEvent();
    final EventPreCreateContext context = new EventPreCreateContextImpl();
    for (int i = 0; i < poolSize; i++) {
        ecs.submit(new Callable<String>() {
            @Override/* ww  w .j  a  v a  2s.co m*/
            public String call() throws Exception {
                barrier.await();
                return eventSummaryDao.create(event, context);
            }
        });
    }
    String uuid = null;
    for (int i = 0; i < poolSize; i++) {
        String thisUuid = ecs.take().get();
        if (uuid == null) {
            assertNotNull(thisUuid);
            uuid = thisUuid;
        } else {
            assertEquals(uuid, thisUuid);
        }
    }
    // Now look up the event and make sure the count is equal to the number of submitted workers
    assertEquals(poolSize, this.eventSummaryDao.findByUuid(uuid).getCount());
}

From source file:org.springframework.integration.zookeeper.metadata.ZookeeperMetadataStoreTests.java

@Test
public void testListenerInvokedOnLocalChanges() throws Exception {
    String testKey = "ZookeeperMetadataStoreTests";

    // register listeners
    final List<List<String>> notifiedChanges = new ArrayList<List<String>>();
    final Map<String, CyclicBarrier> barriers = new HashMap<String, CyclicBarrier>();
    barriers.put("add", new CyclicBarrier(2));
    barriers.put("remove", new CyclicBarrier(2));
    barriers.put("update", new CyclicBarrier(2));
    metadataStore.addListener(new MetadataStoreListenerAdapter() {
        @Override//from  www .j a v a 2  s.  c o m
        public void onAdd(String key, String value) {
            notifiedChanges.add(Arrays.asList("add", key, value));
            waitAtBarrier("add", barriers);
        }

        @Override
        public void onRemove(String key, String oldValue) {
            notifiedChanges.add(Arrays.asList("remove", key, oldValue));
            waitAtBarrier("remove", barriers);
        }

        @Override
        public void onUpdate(String key, String newValue) {
            notifiedChanges.add(Arrays.asList("update", key, newValue));
            waitAtBarrier("update", barriers);
        }
    });

    // the tests themselves
    barriers.get("add").reset();
    metadataStore.put(testKey, "Integration");
    waitAtBarrier("add", barriers);
    assertThat(notifiedChanges, hasSize(1));
    assertThat(notifiedChanges.get(0), IsIterableContainingInOrder.contains("add", testKey, "Integration"));

    metadataStore.putIfAbsent(testKey, "Integration++");
    // there is no update and therefore we expect no changes
    assertThat(notifiedChanges, hasSize(1));

    barriers.get("update").reset();
    metadataStore.put(testKey, "Integration-2");
    waitAtBarrier("update", barriers);
    assertThat(notifiedChanges, hasSize(2));
    assertThat(notifiedChanges.get(1),
            IsIterableContainingInOrder.contains("update", testKey, "Integration-2"));

    barriers.get("update").reset();
    metadataStore.replace(testKey, "Integration-2", "Integration-3");
    waitAtBarrier("update", barriers);
    assertThat(notifiedChanges, hasSize(3));
    assertThat(notifiedChanges.get(2),
            IsIterableContainingInOrder.contains("update", testKey, "Integration-3"));

    metadataStore.replace(testKey, "Integration-2", "Integration-none");
    assertThat(notifiedChanges, hasSize(3));

    barriers.get("remove").reset();
    metadataStore.remove(testKey);
    waitAtBarrier("remove", barriers);
    assertThat(notifiedChanges, hasSize(4));
    assertThat(notifiedChanges.get(3),
            IsIterableContainingInOrder.contains("remove", testKey, "Integration-3"));

    // sleep and try to see if there were any other updates
    Thread.sleep(1000);
    assertThat(notifiedChanges, hasSize(4));
}