Search in sources :

Example 46 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project neo4j by neo4j.

the class ConcurrentInstanceStartupIT method concurrentStartupShouldWork.

@Test
public void concurrentStartupShouldWork() throws Exception {
    // Ensures that the instances don't race to create the test's base directory and only care about their own.
    testDirectory.directory("nothingToSeeHereMoveAlong");
    StringBuffer initialHostsBuffer = new StringBuffer("127.0.0.1:5001");
    for (int i = 2; i <= INSTANCE_COUNT; i++) {
        initialHostsBuffer.append(",127.0.0.1:500" + i);
    }
    final String initialHosts = initialHostsBuffer.toString();
    final CyclicBarrier barrier = new CyclicBarrier(INSTANCE_COUNT);
    final List<Thread> daThreads = new ArrayList<Thread>(INSTANCE_COUNT);
    final HighlyAvailableGraphDatabase[] dbs = new HighlyAvailableGraphDatabase[INSTANCE_COUNT];
    for (int i = 1; i <= INSTANCE_COUNT; i++) {
        final int finalI = i;
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    barrier.await();
                    dbs[finalI - 1] = startDbAtBase(finalI, initialHosts);
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        daThreads.add(t);
        t.start();
    }
    for (Thread daThread : daThreads) {
        daThread.join();
    }
    boolean masterDone = false;
    for (HighlyAvailableGraphDatabase db : dbs) {
        if (db.isMaster()) {
            if (masterDone) {
                throw new Exception("Two masters discovered");
            }
            masterDone = true;
        }
        try (Transaction tx = db.beginTx()) {
            db.createNode();
            tx.success();
        }
    }
    assertTrue(masterDone);
    for (HighlyAvailableGraphDatabase db : dbs) {
        db.shutdown();
    }
}
Also used : ArrayList(java.util.ArrayList) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) CyclicBarrier(java.util.concurrent.CyclicBarrier) Transaction(org.neo4j.graphdb.Transaction) Test(org.junit.Test)

Example 47 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project netty by netty.

the class ResourceLeakDetectorTest method testConcurentUsage.

@Test(timeout = 60000)
public void testConcurentUsage() throws Throwable {
    final AtomicBoolean finished = new AtomicBoolean();
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    // With 50 threads issue #6087 is reproducible on every run.
    Thread[] threads = new Thread[50];
    final CyclicBarrier barrier = new CyclicBarrier(threads.length);
    for (int i = 0; i < threads.length; i++) {
        Thread t = new Thread(new Runnable() {

            Queue<LeakAwareResource> resources = new ArrayDeque<LeakAwareResource>(100);

            @Override
            public void run() {
                try {
                    barrier.await();
                    // Run 10000 times or until the test is marked as finished.
                    for (int b = 0; b < 1000 && !finished.get(); b++) {
                        // Allocate 100 LeakAwareResource per run and close them after it.
                        for (int a = 0; a < 100; a++) {
                            DefaultResource resource = new DefaultResource();
                            ResourceLeakTracker<Resource> leak = DefaultResource.detector.track(resource);
                            LeakAwareResource leakAwareResource = new LeakAwareResource(resource, leak);
                            resources.add(leakAwareResource);
                        }
                        if (closeResources(true)) {
                            finished.set(true);
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Throwable e) {
                    error.compareAndSet(null, e);
                } finally {
                    // Just close all resource now without assert it to eliminate more reports.
                    closeResources(false);
                }
            }

            private boolean closeResources(boolean checkClosed) {
                for (; ; ) {
                    LeakAwareResource r = resources.poll();
                    if (r == null) {
                        return false;
                    }
                    boolean closed = r.close();
                    if (checkClosed && !closed) {
                        error.compareAndSet(null, new AssertionError("ResourceLeak.close() returned 'false' but expected 'true'"));
                        return true;
                    }
                }
            }
        });
        threads[i] = t;
        t.start();
    }
    // Just wait until all threads are done.
    for (Thread t : threads) {
        t.join();
    }
    // Check if we had any leak reports in the ResourceLeakDetector itself
    DefaultResource.detector.assertNoErrors();
    assertNoErrors(error);
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayDeque(java.util.ArrayDeque) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 48 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project druid by druid-io.

the class NamedIntrospectionHandler method testConcurrencyStartStoooooooooop.

@Test
public void testConcurrencyStartStoooooooooop() throws Exception {
    lookupReferencesManager.stop();
    lookupReferencesManager.start();
    final CyclicBarrier cyclicBarrier = new CyclicBarrier(CONCURRENT_THREADS);
    final Runnable start = new Runnable() {

        @Override
        public void run() {
            try {
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                throw Throwables.propagate(e);
            }
            lookupReferencesManager.stop();
        }
    };
    final Collection<ListenableFuture<?>> futures = new ArrayList<>(CONCURRENT_THREADS);
    for (int i = 0; i < CONCURRENT_THREADS; ++i) {
        futures.add(executorService.submit(start));
    }
    Futures.allAsList(futures).get(100, TimeUnit.MILLISECONDS);
    for (ListenableFuture future : futures) {
        Assert.assertNull(future.get());
    }
}
Also used : BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ArrayList(java.util.ArrayList) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) CyclicBarrier(java.util.concurrent.CyclicBarrier) Test(org.junit.Test)

Example 49 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project druid by druid-io.

the class BytesBoundedLinkedQueueTest method testOfferAndPut.

@Test
public void testOfferAndPut() throws Exception {
    final BlockingQueue<TestObject> q = getQueue(10);
    try {
        q.offer(null);
        Assert.fail();
    } catch (NullPointerException success) {
    }
    final TestObject obj = new TestObject(2);
    while (q.remainingCapacity() > 0) {
        Assert.assertTrue(q.offer(obj, delayMS, TimeUnit.MILLISECONDS));
    }
    // queue full
    Assert.assertEquals(0, q.remainingCapacity());
    Assert.assertFalse(q.offer(obj, delayMS, TimeUnit.MILLISECONDS));
    Assert.assertFalse(q.offer(obj));
    final CyclicBarrier barrier = new CyclicBarrier(2);
    Future<Boolean> future = exec.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            barrier.await();
            Assert.assertTrue(q.offer(obj, delayMS, TimeUnit.MILLISECONDS));
            Assert.assertEquals(q.remainingCapacity(), 0);
            barrier.await();
            q.put(obj);
            return true;
        }
    });
    barrier.await();
    q.take();
    barrier.await();
    q.take();
    Assert.assertTrue(future.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TimeoutException(java.util.concurrent.TimeoutException) CyclicBarrier(java.util.concurrent.CyclicBarrier) Test(org.junit.Test)

Example 50 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project hadoop by apache.

the class TestStringUtils method testGetFormattedTimeWithDiff.

@Test
public //Multithreaded Test GetFormattedTimeWithDiff()
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
            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);
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) TraditionalBinaryPrefix.long2String(org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix.long2String) CyclicBarrier(java.util.concurrent.CyclicBarrier) Test(org.junit.Test)

Aggregations

CyclicBarrier (java.util.concurrent.CyclicBarrier)650 Test (org.junit.Test)315 CountDownLatch (java.util.concurrent.CountDownLatch)169 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)142 ArrayList (java.util.ArrayList)126 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)124 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)121 IOException (java.io.IOException)97 ExecutorService (java.util.concurrent.ExecutorService)84 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)67 AtomicReference (java.util.concurrent.atomic.AtomicReference)66 Ignite (org.apache.ignite.Ignite)64 List (java.util.List)53 Test (org.testng.annotations.Test)52 TimeoutException (java.util.concurrent.TimeoutException)48 Transaction (org.apache.ignite.transactions.Transaction)48 IgniteException (org.apache.ignite.IgniteException)47 ExecutionException (java.util.concurrent.ExecutionException)40 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)40 IgniteCache (org.apache.ignite.IgniteCache)37