Search in sources :

Example 41 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project elasticsearch by elastic.

the class RetryTests method blockExecutor.

/**
     * Blocks the named executor by getting its only thread running a task blocked on a CyclicBarrier and fills the queue with a noop task.
     * So requests to use this queue should get {@link EsRejectedExecutionException}s.
     */
private CyclicBarrier blockExecutor(String name) throws Exception {
    ThreadPool threadPool = getInstanceFromNode(ThreadPool.class);
    CyclicBarrier barrier = new CyclicBarrier(2);
    logger.info("Blocking the [{}] executor", name);
    threadPool.executor(name).execute(() -> {
        try {
            threadPool.executor(name).execute(() -> {
            });
            barrier.await();
            logger.info("Blocked the [{}] executor", name);
            barrier.await();
            logger.info("Unblocking the [{}] executor", name);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
    barrier.await();
    blockedExecutors.add(barrier);
    return barrier;
}
Also used : ThreadPool(org.elasticsearch.threadpool.ThreadPool) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) CyclicBarrier(java.util.concurrent.CyclicBarrier)

Example 42 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project jetty.project by eclipse.

the class BlockingArrayQueueTest method testConcurrentAccess.

@Test
@Slow
public void testConcurrentAccess() throws Exception {
    final int THREADS = 50;
    final int LOOPS = 1000;
    final BlockingArrayQueue<Integer> queue = new BlockingArrayQueue<>(1 + THREADS * LOOPS);
    final ConcurrentLinkedQueue<Integer> produced = new ConcurrentLinkedQueue<>();
    final ConcurrentLinkedQueue<Integer> consumed = new ConcurrentLinkedQueue<>();
    final AtomicBoolean running = new AtomicBoolean(true);
    // start consumers
    final CyclicBarrier barrier0 = new CyclicBarrier(THREADS + 1);
    for (int i = 0; i < THREADS; i++) {
        new Thread() {

            @Override
            public void run() {
                final Random random = new Random();
                setPriority(getPriority() - 1);
                try {
                    while (running.get()) {
                        int r = 1 + random.nextInt(10);
                        if (r % 2 == 0) {
                            Integer msg = queue.poll();
                            if (msg == null) {
                                Thread.sleep(1 + random.nextInt(10));
                                continue;
                            }
                            consumed.add(msg);
                        } else {
                            Integer msg = queue.poll(r, TimeUnit.MILLISECONDS);
                            if (msg != null)
                                consumed.add(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        barrier0.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    // start producers
    final CyclicBarrier barrier1 = new CyclicBarrier(THREADS + 1);
    for (int i = 0; i < THREADS; i++) {
        final int id = i;
        new Thread() {

            @Override
            public void run() {
                final Random random = new Random();
                try {
                    for (int j = 0; j < LOOPS; j++) {
                        Integer msg = random.nextInt();
                        produced.add(msg);
                        if (!queue.offer(msg))
                            throw new Exception(id + " FULL! " + queue.size());
                        Thread.sleep(1 + random.nextInt(10));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        barrier1.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    barrier1.await();
    int size = queue.size();
    int last = size - 1;
    while (size > 0 && size != last) {
        last = size;
        Thread.sleep(500);
        size = queue.size();
    }
    running.set(false);
    barrier0.await();
    HashSet<Integer> prodSet = new HashSet<>(produced);
    HashSet<Integer> consSet = new HashSet<>(consumed);
    Assert.assertEquals(prodSet, consSet);
}
Also used : CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Random(java.util.Random) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) HashSet(java.util.HashSet) Test(org.junit.Test) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow)

Example 43 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project elasticsearch by elastic.

the class NodeJoinControllerTests method testNormalConcurrentJoins.

public void testNormalConcurrentJoins() throws InterruptedException {
    Thread[] threads = new Thread[3 + randomInt(5)];
    ArrayList<DiscoveryNode> nodes = new ArrayList<>();
    nodes.add(clusterService.localNode());
    final CyclicBarrier barrier = new CyclicBarrier(threads.length);
    final List<Throwable> backgroundExceptions = new CopyOnWriteArrayList<>();
    for (int i = 0; i < threads.length; i++) {
        final DiscoveryNode node = newNode(i);
        final int iterations = rarely() ? randomIntBetween(1, 4) : 1;
        nodes.add(node);
        threads[i] = new Thread(new AbstractRunnable() {

            @Override
            public void onFailure(Exception e) {
                logger.error("unexpected error in join thread", e);
                backgroundExceptions.add(e);
            }

            @Override
            protected void doRun() throws Exception {
                barrier.await();
                for (int i = 0; i < iterations; i++) {
                    logger.debug("{} joining", node);
                    joinNode(node);
                }
            }
        }, "t_" + i);
        threads[i].start();
    }
    logger.info("--> waiting for joins to complete");
    for (Thread thread : threads) {
        thread.join();
    }
    assertNodesInCurrentState(nodes);
}
Also used : AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) NotMasterException(org.elasticsearch.cluster.NotMasterException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ExecutionException(java.util.concurrent.ExecutionException) CyclicBarrier(java.util.concurrent.CyclicBarrier) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 44 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project elasticsearch by elastic.

the class NodeJoinControllerTests method testElectionWithConcurrentJoins.

public void testElectionWithConcurrentJoins() throws InterruptedException, BrokenBarrierException {
    DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.builder(clusterService.state().nodes()).masterNodeId(null);
    setState(clusterService, ClusterState.builder(clusterService.state()).nodes(nodesBuilder));
    nodeJoinController.startElectionContext();
    Thread[] threads = new Thread[3 + randomInt(5)];
    final int requiredJoins = randomInt(threads.length);
    ArrayList<DiscoveryNode> nodes = new ArrayList<>();
    nodes.add(clusterService.localNode());
    final CyclicBarrier barrier = new CyclicBarrier(threads.length + 1);
    final List<Throwable> backgroundExceptions = new CopyOnWriteArrayList<>();
    for (int i = 0; i < threads.length; i++) {
        final DiscoveryNode node = newNode(i, true);
        final int iterations = rarely() ? randomIntBetween(1, 4) : 1;
        nodes.add(node);
        threads[i] = new Thread(new AbstractRunnable() {

            @Override
            public void onFailure(Exception e) {
                logger.error("unexpected error in join thread", e);
                backgroundExceptions.add(e);
            }

            @Override
            protected void doRun() throws Exception {
                barrier.await();
                for (int i = 0; i < iterations; i++) {
                    logger.debug("{} joining", node);
                    joinNode(node);
                }
            }
        }, "t_" + i);
        threads[i].start();
    }
    barrier.await();
    logger.info("--> waiting to be elected as master (required joins [{}])", requiredJoins);
    final AtomicReference<Throwable> failure = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    nodeJoinController.waitToBeElectedAsMaster(requiredJoins, TimeValue.timeValueHours(30), new NodeJoinController.ElectionCallback() {

        @Override
        public void onElectedAsMaster(ClusterState state) {
            assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(), equalTo(true));
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            logger.error("unexpected error while waiting to be elected as master", t);
            failure.set(t);
            latch.countDown();
        }
    });
    latch.await();
    ExceptionsHelper.reThrowIfNotNull(failure.get());
    logger.info("--> waiting for joins to complete");
    for (Thread thread : threads) {
        thread.join();
    }
    assertNodesInCurrentState(nodes);
}
Also used : AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) NotMasterException(org.elasticsearch.cluster.NotMasterException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ExecutionException(java.util.concurrent.ExecutionException) CyclicBarrier(java.util.concurrent.CyclicBarrier) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 45 with CyclicBarrier

use of java.util.concurrent.CyclicBarrier in project elasticsearch by elastic.

the class InternalEngineTests method testSequenceNumberAdvancesToMaxSeqOnEngineOpenOnPrimary.

public void testSequenceNumberAdvancesToMaxSeqOnEngineOpenOnPrimary() throws BrokenBarrierException, InterruptedException, IOException {
    engine.close();
    final int docs = randomIntBetween(1, 32);
    InternalEngine initialEngine = null;
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        final CyclicBarrier barrier = new CyclicBarrier(2);
        final AtomicBoolean skip = new AtomicBoolean();
        final AtomicLong expectedLocalCheckpoint = new AtomicLong(SequenceNumbersService.NO_OPS_PERFORMED);
        final List<Thread> threads = new ArrayList<>();
        final SequenceNumbersService seqNoService = new SequenceNumbersService(shardId, defaultSettings, SequenceNumbersService.NO_OPS_PERFORMED, SequenceNumbersService.NO_OPS_PERFORMED, SequenceNumbersService.UNASSIGNED_SEQ_NO) {

            @Override
            public long generateSeqNo() {
                final long seqNo = super.generateSeqNo();
                if (skip.get()) {
                    try {
                        barrier.await();
                        latch.await();
                    } catch (BrokenBarrierException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    if (expectedLocalCheckpoint.get() + 1 == seqNo) {
                        expectedLocalCheckpoint.set(seqNo);
                    }
                }
                return seqNo;
            }
        };
        initialEngine = createEngine(defaultSettings, store, primaryTranslogDir, newMergePolicy(), null, () -> seqNoService);
        final InternalEngine finalInitialEngine = initialEngine;
        for (int i = 0; i < docs; i++) {
            final String id = Integer.toString(i);
            final ParsedDocument doc = testParsedDocument(id, "test", null, testDocumentWithTextField(), SOURCE, null);
            skip.set(randomBoolean());
            final Thread thread = new Thread(() -> {
                try {
                    finalInitialEngine.index(indexForDoc(doc));
                } catch (IOException e) {
                    throw new AssertionError(e);
                }
            });
            thread.start();
            if (skip.get()) {
                threads.add(thread);
                barrier.await();
            } else {
                thread.join();
            }
        }
        assertThat(initialEngine.seqNoService().getLocalCheckpoint(), equalTo(expectedLocalCheckpoint.get()));
        assertThat(initialEngine.seqNoService().getMaxSeqNo(), equalTo((long) (docs - 1)));
        initialEngine.flush(true, true);
        latch.countDown();
        for (final Thread thread : threads) {
            thread.join();
        }
    } finally {
        IOUtils.close(initialEngine);
    }
    try (Engine recoveringEngine = new InternalEngine(copy(initialEngine.config(), EngineConfig.OpenMode.OPEN_INDEX_AND_TRANSLOG))) {
        assertThat(recoveringEngine.seqNoService().getLocalCheckpoint(), greaterThanOrEqualTo((long) (docs - 1)));
    }
}
Also used : BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) LongPoint(org.apache.lucene.document.LongPoint) CyclicBarrier(java.util.concurrent.CyclicBarrier) SequenceNumbersService(org.elasticsearch.index.seqno.SequenceNumbersService) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument)

Aggregations

CyclicBarrier (java.util.concurrent.CyclicBarrier)366 Test (org.junit.Test)128 CountDownLatch (java.util.concurrent.CountDownLatch)96 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)85 ArrayList (java.util.ArrayList)78 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)75 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)73 IOException (java.io.IOException)66 ExecutorService (java.util.concurrent.ExecutorService)45 Ignite (org.apache.ignite.Ignite)41 AtomicReference (java.util.concurrent.atomic.AtomicReference)40 IgniteException (org.apache.ignite.IgniteException)35 List (java.util.List)33 IgniteCache (org.apache.ignite.IgniteCache)27 Test (org.testng.annotations.Test)27 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)24 TimeoutException (java.util.concurrent.TimeoutException)23 Transaction (org.apache.ignite.transactions.Transaction)23 ExecutionException (java.util.concurrent.ExecutionException)22 Callable (java.util.concurrent.Callable)20