Search in sources :

Example 31 with CyclicBarrier

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

the class CounterStatisticTest method testCounterContended.

@Test
public void testCounterContended() throws Exception {
    final CounterStatistic counter = new CounterStatistic();
    final int N = 100;
    final int L = 1000;
    final Thread[] threads = new Thread[N];
    final CyclicBarrier incBarrier = new CyclicBarrier(N);
    final CountDownLatch decBarrier = new CountDownLatch(N / 2);
    for (int i = N; i-- > 0; ) {
        final int I = i;
        threads[i] = (i >= N / 2) ? new Thread() {

            @Override
            public void run() {
                try {
                    incBarrier.await();
                    decBarrier.await();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                Random random = new Random();
                for (int l = L; l-- > 0; ) {
                    counter.decrement();
                    if (random.nextInt(5) == 0)
                        Thread.yield();
                }
            }
        } : new Thread() {

            @Override
            public void run() {
                try {
                    incBarrier.await();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                Random random = new Random();
                for (int l = L; l-- > 0; ) {
                    counter.increment();
                    if (l == L / 2)
                        decBarrier.countDown();
                    if (random.nextInt(5) == 0)
                        Thread.yield();
                }
            }
        };
        threads[i].start();
    }
    for (int i = N; i-- > 0; ) threads[i].join();
    assertThat(counter.getCurrent(), equalTo(0L));
    assertThat(counter.getTotal(), equalTo(N * L / 2L));
    assertThat(counter.getMax(), greaterThanOrEqualTo((N / 2) * (L / 2L)));
}
Also used : Random(java.util.Random) CountDownLatch(java.util.concurrent.CountDownLatch) CyclicBarrier(java.util.concurrent.CyclicBarrier) Test(org.junit.Test)

Example 32 with CyclicBarrier

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

the class AbstractSimpleTransportTestCase method testConcurrentSendRespondAndDisconnect.

public void testConcurrentSendRespondAndDisconnect() throws BrokenBarrierException, InterruptedException {
    Set<Exception> sendingErrors = ConcurrentCollections.newConcurrentSet();
    Set<Exception> responseErrors = ConcurrentCollections.newConcurrentSet();
    serviceA.registerRequestHandler("test", TestRequest::new, randomBoolean() ? ThreadPool.Names.SAME : ThreadPool.Names.GENERIC, (request, channel) -> {
        try {
            channel.sendResponse(new TestResponse());
        } catch (Exception e) {
            logger.info("caught exception while responding", e);
            responseErrors.add(e);
        }
    });
    final TransportRequestHandler<TestRequest> ignoringRequestHandler = (request, channel) -> {
        try {
            channel.sendResponse(new TestResponse());
        } catch (Exception e) {
            // we don't really care what's going on B, we're testing through A
            logger.trace("caught exception while responding from node B", e);
        }
    };
    serviceB.registerRequestHandler("test", TestRequest::new, ThreadPool.Names.SAME, ignoringRequestHandler);
    int halfSenders = scaledRandomIntBetween(3, 10);
    final CyclicBarrier go = new CyclicBarrier(halfSenders * 2 + 1);
    final CountDownLatch done = new CountDownLatch(halfSenders * 2);
    for (int i = 0; i < halfSenders; i++) {
        // B senders just generated activity so serciveA can respond, we don't test what's going on there
        final int sender = i;
        threadPool.executor(ThreadPool.Names.GENERIC).execute(new AbstractRunnable() {

            @Override
            public void onFailure(Exception e) {
                logger.trace("caught exception while sending from B", e);
            }

            @Override
            protected void doRun() throws Exception {
                go.await();
                for (int iter = 0; iter < 10; iter++) {
                    PlainActionFuture<TestResponse> listener = new PlainActionFuture<>();
                    final String info = sender + "_B_" + iter;
                    serviceB.sendRequest(nodeA, "test", new TestRequest(info), new ActionListenerResponseHandler<>(listener, TestResponse::new));
                    try {
                        listener.actionGet();
                    } catch (Exception e) {
                        logger.trace((Supplier<?>) () -> new ParameterizedMessage("caught exception while sending to node {}", nodeA), e);
                    }
                }
            }

            @Override
            public void onAfter() {
                done.countDown();
            }
        });
    }
    for (int i = 0; i < halfSenders; i++) {
        final int sender = i;
        threadPool.executor(ThreadPool.Names.GENERIC).execute(new AbstractRunnable() {

            @Override
            public void onFailure(Exception e) {
                logger.error("unexpected error", e);
                sendingErrors.add(e);
            }

            @Override
            protected void doRun() throws Exception {
                go.await();
                for (int iter = 0; iter < 10; iter++) {
                    PlainActionFuture<TestResponse> listener = new PlainActionFuture<>();
                    final String info = sender + "_" + iter;
                    // capture now
                    final DiscoveryNode node = nodeB;
                    try {
                        serviceA.sendRequest(node, "test", new TestRequest(info), new ActionListenerResponseHandler<>(listener, TestResponse::new));
                        try {
                            listener.actionGet();
                        } catch (ConnectTransportException e) {
                        // ok!
                        } catch (Exception e) {
                            logger.error((Supplier<?>) () -> new ParameterizedMessage("caught exception while sending to node {}", node), e);
                            sendingErrors.add(e);
                        }
                    } catch (NodeNotConnectedException ex) {
                    // ok
                    }
                }
            }

            @Override
            public void onAfter() {
                done.countDown();
            }
        });
    }
    go.await();
    for (int i = 0; i <= 10; i++) {
        if (i % 3 == 0) {
            // simulate restart of nodeB
            serviceB.close();
            MockTransportService newService = buildService("TS_B_" + i, version1, null);
            newService.registerRequestHandler("test", TestRequest::new, ThreadPool.Names.SAME, ignoringRequestHandler);
            serviceB = newService;
            nodeB = newService.getLocalDiscoNode();
            serviceB.connectToNode(nodeA);
            serviceA.connectToNode(nodeB);
        } else if (serviceA.nodeConnected(nodeB)) {
            serviceA.disconnectFromNode(nodeB);
        } else {
            serviceA.connectToNode(nodeB);
        }
    }
    done.await();
    assertThat("found non connection errors while sending", sendingErrors, empty());
    assertThat("found non connection errors while responding", responseErrors, empty());
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) Arrays(java.util.Arrays) BigArrays(org.elasticsearch.common.util.BigArrays) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) CyclicBarrier(java.util.concurrent.CyclicBarrier) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Matchers.startsWith(org.hamcrest.Matchers.startsWith) UncheckedIOException(java.io.UncheckedIOException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) List(java.util.List) Version(org.elasticsearch.Version) TransportAddress(org.elasticsearch.common.transport.TransportAddress) Supplier(org.apache.logging.log4j.util.Supplier) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Socket(java.net.Socket) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) TimeValue(org.elasticsearch.common.unit.TimeValue) Node(org.elasticsearch.node.Node) ESTestCase(org.elasticsearch.test.ESTestCase) MockTransportService(org.elasticsearch.test.transport.MockTransportService) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) Collections.emptySet(java.util.Collections.emptySet) Semaphore(java.util.concurrent.Semaphore) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) VersionUtils(org.elasticsearch.test.VersionUtils) CollectionUtil(org.apache.lucene.util.CollectionUtil) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) Constants(org.apache.lucene.util.Constants) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Collections(java.util.Collections) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) CountDownLatch(java.util.concurrent.CountDownLatch) ElasticsearchException(org.elasticsearch.ElasticsearchException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ExecutionException(java.util.concurrent.ExecutionException) CyclicBarrier(java.util.concurrent.CyclicBarrier) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage)

Example 33 with CyclicBarrier

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

the class TasksIT method testNodeNotFoundButTaskFound.

public void testNodeNotFoundButTaskFound() throws Exception {
    // Save a fake task that looks like it is from a node that isn't part of the cluster
    CyclicBarrier b = new CyclicBarrier(2);
    TaskResultsService resultsService = internalCluster().getInstance(TaskResultsService.class);
    resultsService.storeResult(new TaskResult(new TaskInfo(new TaskId("fake", 1), "test", "test", "", null, 0, 0, false, TaskId.EMPTY_TASK_ID), new RuntimeException("test")), new ActionListener<Void>() {

        @Override
        public void onResponse(Void response) {
            try {
                b.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception e) {
            throw new RuntimeException(e);
        }
    });
    b.await();
    // Now we can find it!
    GetTaskResponse response = expectFinishedTask(new TaskId("fake:1"));
    assertEquals("test", response.getTask().getTask().getAction());
    assertNotNull(response.getTask().getError());
    assertNull(response.getTask().getResponse());
}
Also used : TaskInfo(org.elasticsearch.tasks.TaskInfo) TaskId(org.elasticsearch.tasks.TaskId) TaskResult(org.elasticsearch.tasks.TaskResult) GetTaskResponse(org.elasticsearch.action.admin.cluster.node.tasks.get.GetTaskResponse) TaskResultsService(org.elasticsearch.tasks.TaskResultsService) FailedNodeException(org.elasticsearch.action.FailedNodeException) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) CyclicBarrier(java.util.concurrent.CyclicBarrier)

Example 34 with CyclicBarrier

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

the class UpdateMappingIntegrationIT method testUpdateMappingConcurrently.

public void testUpdateMappingConcurrently() throws Throwable {
    createIndex("test1", "test2");
    final AtomicReference<Exception> threadException = new AtomicReference<>();
    final AtomicBoolean stop = new AtomicBoolean(false);
    Thread[] threads = new Thread[3];
    final CyclicBarrier barrier = new CyclicBarrier(threads.length);
    final ArrayList<Client> clientArray = new ArrayList<>();
    for (Client c : clients()) {
        clientArray.add(c);
    }
    for (int j = 0; j < threads.length; j++) {
        threads[j] = new Thread(new Runnable() {

            @SuppressWarnings("unchecked")
            @Override
            public void run() {
                try {
                    barrier.await();
                    for (int i = 0; i < 100; i++) {
                        if (stop.get()) {
                            return;
                        }
                        Client client1 = clientArray.get(i % clientArray.size());
                        Client client2 = clientArray.get((i + 1) % clientArray.size());
                        String indexName = i % 2 == 0 ? "test2" : "test1";
                        String typeName = "type" + (i % 10);
                        String fieldName = Thread.currentThread().getName() + "_" + i;
                        PutMappingResponse response = client1.admin().indices().preparePutMapping(indexName).setType(typeName).setSource(JsonXContent.contentBuilder().startObject().startObject(typeName).startObject("properties").startObject(fieldName).field("type", "text").endObject().endObject().endObject().endObject()).get();
                        assertThat(response.isAcknowledged(), equalTo(true));
                        GetMappingsResponse getMappingResponse = client2.admin().indices().prepareGetMappings(indexName).get();
                        ImmutableOpenMap<String, MappingMetaData> mappings = getMappingResponse.getMappings().get(indexName);
                        assertThat(mappings.containsKey(typeName), equalTo(true));
                        assertThat(((Map<String, Object>) mappings.get(typeName).getSourceAsMap().get("properties")).keySet(), Matchers.hasItem(fieldName));
                    }
                } catch (Exception e) {
                    threadException.set(e);
                    stop.set(true);
                }
            }
        });
        threads[j].setName("t_" + j);
        threads[j].start();
    }
    for (Thread t : threads) t.join();
    if (threadException.get() != null) {
        throw threadException.get();
    }
}
Also used : ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException) IOException(java.io.IOException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PutMappingResponse(org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse) Client(org.elasticsearch.client.Client) GetMappingsResponse(org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse)

Example 35 with CyclicBarrier

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

the class RemoteClusterConnectionTests method testCloseWhileConcurrentlyConnecting.

public void testCloseWhileConcurrentlyConnecting() throws IOException, InterruptedException, BrokenBarrierException {
    List<DiscoveryNode> knownNodes = new CopyOnWriteArrayList<>();
    try (MockTransportService seedTransport = startTransport("seed_node", knownNodes, Version.CURRENT);
        MockTransportService seedTransport1 = startTransport("seed_node_1", knownNodes, Version.CURRENT);
        MockTransportService discoverableTransport = startTransport("discoverable_node", knownNodes, Version.CURRENT)) {
        DiscoveryNode seedNode = seedTransport.getLocalDiscoNode();
        DiscoveryNode seedNode1 = seedTransport1.getLocalDiscoNode();
        knownNodes.add(seedTransport.getLocalDiscoNode());
        knownNodes.add(discoverableTransport.getLocalDiscoNode());
        knownNodes.add(seedTransport1.getLocalDiscoNode());
        Collections.shuffle(knownNodes, random());
        List<DiscoveryNode> seedNodes = Arrays.asList(seedNode1, seedNode);
        Collections.shuffle(seedNodes, random());
        try (MockTransportService service = MockTransportService.createNewService(Settings.EMPTY, Version.CURRENT, threadPool, null)) {
            service.start();
            service.acceptIncomingRequests();
            try (RemoteClusterConnection connection = new RemoteClusterConnection(Settings.EMPTY, "test-cluster", seedNodes, service, Integer.MAX_VALUE, n -> true)) {
                int numThreads = randomIntBetween(4, 10);
                Thread[] threads = new Thread[numThreads];
                CyclicBarrier barrier = new CyclicBarrier(numThreads + 1);
                for (int i = 0; i < threads.length; i++) {
                    final int numConnectionAttempts = randomIntBetween(10, 100);
                    threads[i] = new Thread() {

                        @Override
                        public void run() {
                            try {
                                barrier.await();
                                CountDownLatch latch = new CountDownLatch(numConnectionAttempts);
                                for (int i = 0; i < numConnectionAttempts; i++) {
                                    AtomicReference<RuntimeException> executed = new AtomicReference<>();
                                    ActionListener<Void> listener = ActionListener.wrap(x -> {
                                        if (executed.compareAndSet(null, new RuntimeException())) {
                                            latch.countDown();
                                        } else {
                                            throw new AssertionError("shit's been called twice", executed.get());
                                        }
                                    }, x -> {
                                        if (executed.compareAndSet(null, new RuntimeException())) {
                                            latch.countDown();
                                        } else {
                                            throw new AssertionError("shit's been called twice", executed.get());
                                        }
                                        if (x instanceof RejectedExecutionException || x instanceof AlreadyClosedException || x instanceof CancellableThreads.ExecutionCancelledException) {
                                        } else {
                                            throw new AssertionError(x);
                                        }
                                    });
                                    connection.updateSeedNodes(seedNodes, listener);
                                }
                                latch.await();
                            } catch (Exception ex) {
                                throw new AssertionError(ex);
                            }
                        }
                    };
                    threads[i].start();
                }
                barrier.await();
                connection.close();
            }
        }
    }
}
Also used : CancellableThreads(org.elasticsearch.common.util.CancellableThreads) Socket(java.net.Socket) Arrays(java.util.Arrays) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AlreadyConnectedException(java.nio.channels.AlreadyConnectedException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClusterSearchShardsRequest(org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsRequest) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Settings(org.elasticsearch.common.settings.Settings) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) ESTestCase(org.elasticsearch.test.ESTestCase) MockTransportService(org.elasticsearch.test.transport.MockTransportService) ClusterSearchShardsAction(org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsAction) ClusterSearchShardsGroup(org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsGroup) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) CyclicBarrier(java.util.concurrent.CyclicBarrier) Collections.emptySet(java.util.Collections.emptySet) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) ClusterSearchShardsResponse(org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsResponse) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) UncheckedIOException(java.io.UncheckedIOException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Version(org.elasticsearch.Version) SuppressForbidden(org.elasticsearch.common.SuppressForbidden) TransportAddress(org.elasticsearch.common.transport.TransportAddress) TransportConnectionListener(org.elasticsearch.transport.TransportConnectionListener) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) ClusterStateAction(org.elasticsearch.action.admin.cluster.state.ClusterStateAction) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) AtomicReference(java.util.concurrent.atomic.AtomicReference) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) CountDownLatch(java.util.concurrent.CountDownLatch) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AlreadyConnectedException(java.nio.channels.AlreadyConnectedException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) UnknownHostException(java.net.UnknownHostException) UncheckedIOException(java.io.UncheckedIOException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ActionListener(org.elasticsearch.action.ActionListener) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

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