Search in sources :

Example 61 with CopyOnWriteArrayList

use of java.util.concurrent.CopyOnWriteArrayList in project rxjava2-jdbc by davidmoten.

the class DatabaseTest method testDelayedCallsAreNonBlocking.

@Test
public void testDelayedCallsAreNonBlocking() throws InterruptedException {
    List<String> list = new CopyOnWriteArrayList<String>();
    //
    Database db = db(1);
    //
    db.select("select score from person where name=?").parameters(//
    "FRED").getAs(//
    Integer.class).doOnNext(//
    x -> Thread.sleep(1000)).subscribeOn(//
    Schedulers.io()).subscribe();
    Thread.sleep(100);
    CountDownLatch latch = new CountDownLatch(1);
    //
    db.select("select score from person where name=?").parameters(//
    "FRED").getAs(//
    Integer.class).doOnNext(//
    x -> list.add("emitted")).doOnNext(//
    x -> System.out.println("emitted on " + Thread.currentThread().getName())).doOnNext(//
    x -> latch.countDown()).subscribe();
    list.add("subscribed");
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(Arrays.asList("subscribed", "emitted"), list);
}
Also used : Arrays(java.util.Arrays) Connection(java.sql.Connection) Date(java.util.Date) ZonedDateTime(java.time.ZonedDateTime) Completable(io.reactivex.Completable) LoggerFactory(org.slf4j.LoggerFactory) ColumnIndexOutOfRangeException(org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException) MoreColumnsRequestedThanExistException(org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException) NonBlockingConnectionPool(org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool) ByteArrayInputStream(java.io.ByteArrayInputStream) Level(org.apache.log4j.Level) DatabaseCreator(org.davidmoten.rx.jdbc.pool.DatabaseCreator) PoolClosedException(org.davidmoten.rx.jdbc.pool.PoolClosedException) Schedulers(io.reactivex.schedulers.Schedulers) ZoneOffset(java.time.ZoneOffset) QueryAnnotationMissingException(org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException) Pools(org.davidmoten.rx.jdbc.pool.Pools) Reader(java.io.Reader) Instant(java.time.Instant) Column(org.davidmoten.rx.jdbc.annotations.Column) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Index(org.davidmoten.rx.jdbc.annotations.Index) TestScheduler(io.reactivex.schedulers.TestScheduler) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) AnnotationsNotFoundException(org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException) Tuple6(org.davidmoten.rx.jdbc.tuple.Tuple6) NamedParameterMissingException(org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException) Tuple7(org.davidmoten.rx.jdbc.tuple.Tuple7) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Tuple2(org.davidmoten.rx.jdbc.tuple.Tuple2) Tuple3(org.davidmoten.rx.jdbc.tuple.Tuple3) Tuple4(org.davidmoten.rx.jdbc.tuple.Tuple4) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) Tuple5(org.davidmoten.rx.jdbc.tuple.Tuple5) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Single(io.reactivex.Single) ColumnNotFoundException(org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException) Flowable(io.reactivex.Flowable) Observable(io.reactivex.Observable) TestSubscriber(io.reactivex.subscribers.TestSubscriber) Query(org.davidmoten.rx.jdbc.annotations.Query) Logger(org.slf4j.Logger) TupleN(org.davidmoten.rx.jdbc.tuple.TupleN) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Predicate(io.reactivex.functions.Predicate) TimeUnit(java.util.concurrent.TimeUnit) LogManager(org.apache.log4j.LogManager) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) CountDownLatch(java.util.concurrent.CountDownLatch) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.Test)

Example 62 with CopyOnWriteArrayList

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

the class TransportBroadcastReplicationAction method doExecute.

@Override
protected void doExecute(Task task, Request request, ActionListener<Response> listener) {
    final ClusterState clusterState = clusterService.state();
    List<ShardId> shards = shards(request, clusterState);
    final CopyOnWriteArrayList<ShardResponse> shardsResponses = new CopyOnWriteArrayList();
    if (shards.size() == 0) {
        finishAndNotifyListener(listener, shardsResponses);
    }
    final CountDown responsesCountDown = new CountDown(shards.size());
    for (final ShardId shardId : shards) {
        ActionListener<ShardResponse> shardActionListener = new ActionListener<ShardResponse>() {

            @Override
            public void onResponse(ShardResponse shardResponse) {
                shardsResponses.add(shardResponse);
                logger.trace("{}: got response from {}", actionName, shardId);
                if (responsesCountDown.countDown()) {
                    finishAndNotifyListener(listener, shardsResponses);
                }
            }

            @Override
            public void onFailure(Exception e) {
                logger.trace("{}: got failure from {}", actionName, shardId);
                int totalNumCopies = clusterState.getMetaData().getIndexSafe(shardId.getIndex()).getNumberOfReplicas() + 1;
                ShardResponse shardResponse = newShardResponse();
                ReplicationResponse.ShardInfo.Failure[] failures;
                if (TransportActions.isShardNotAvailableException(e)) {
                    failures = new ReplicationResponse.ShardInfo.Failure[0];
                } else {
                    ReplicationResponse.ShardInfo.Failure failure = new ReplicationResponse.ShardInfo.Failure(shardId, null, e, ExceptionsHelper.status(e), true);
                    failures = new ReplicationResponse.ShardInfo.Failure[totalNumCopies];
                    Arrays.fill(failures, failure);
                }
                shardResponse.setShardInfo(new ReplicationResponse.ShardInfo(totalNumCopies, 0, failures));
                shardsResponses.add(shardResponse);
                if (responsesCountDown.countDown()) {
                    finishAndNotifyListener(listener, shardsResponses);
                }
            }
        };
        shardExecute(task, request, shardId, shardActionListener);
    }
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) CountDown(org.elasticsearch.common.util.concurrent.CountDown) BroadcastShardOperationFailedException(org.elasticsearch.action.support.broadcast.BroadcastShardOperationFailedException) ShardOperationFailedException(org.elasticsearch.action.ShardOperationFailedException) DefaultShardOperationFailedException(org.elasticsearch.action.support.DefaultShardOperationFailedException) ShardId(org.elasticsearch.index.shard.ShardId) ActionListener(org.elasticsearch.action.ActionListener) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 63 with CopyOnWriteArrayList

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

the class WorkingBulkByScrollTaskTests method testDelayAndRethrottle.

/**
     * Furiously rethrottles a delayed request to make sure that we never run it twice.
     */
public void testDelayAndRethrottle() throws IOException, InterruptedException {
    List<Throwable> errors = new CopyOnWriteArrayList<>();
    AtomicBoolean done = new AtomicBoolean();
    int threads = between(1, 10);
    CyclicBarrier waitForShutdown = new CyclicBarrier(threads);
    /*
         * We never end up waiting this long because the test rethrottles over and over again, ratcheting down the delay a random amount
         * each time.
         */
    float originalRequestsPerSecond = (float) randomDoubleBetween(1, 10000, true);
    task.rethrottle(originalRequestsPerSecond);
    TimeValue maxDelay = timeValueSeconds(between(1, 5));
    assertThat(maxDelay.nanos(), greaterThanOrEqualTo(0L));
    int batchSizeForMaxDelay = (int) (maxDelay.seconds() * originalRequestsPerSecond);
    ThreadPool threadPool = new TestThreadPool(getTestName()) {

        @Override
        public ScheduledFuture<?> schedule(TimeValue delay, String name, Runnable command) {
            assertThat(delay.nanos(), both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(maxDelay.nanos())));
            return super.schedule(delay, name, command);
        }
    };
    try {
        task.delayPrepareBulkRequest(threadPool, timeValueNanos(System.nanoTime()), batchSizeForMaxDelay, new AbstractRunnable() {

            @Override
            protected void doRun() throws Exception {
                boolean oldValue = done.getAndSet(true);
                if (oldValue) {
                    throw new RuntimeException("Ran twice oh no!");
                }
            }

            @Override
            public void onFailure(Exception e) {
                errors.add(e);
            }
        });
        // Rethrottle on a random number of threads, on of which is this thread.
        Runnable test = () -> {
            try {
                int rethrottles = 0;
                while (false == done.get()) {
                    float requestsPerSecond = (float) randomDoubleBetween(0, originalRequestsPerSecond * 2, true);
                    task.rethrottle(requestsPerSecond);
                    rethrottles += 1;
                }
                logger.info("Rethrottled [{}] times", rethrottles);
                waitForShutdown.await();
            } catch (Exception e) {
                errors.add(e);
            }
        };
        for (int i = 1; i < threads; i++) {
            threadPool.generic().execute(test);
        }
        test.run();
    } finally {
        // Other threads should finish up quickly as they are checking the same AtomicBoolean.
        threadPool.shutdown();
        threadPool.awaitTermination(10, TimeUnit.SECONDS);
    }
    assertThat(errors, empty());
}
Also used : AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) TimeValue(org.elasticsearch.common.unit.TimeValue) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 64 with CopyOnWriteArrayList

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

the class RemoteClusterConnectionTests method testDiscoverSingleNodeWithIncompatibleSeed.

public void testDiscoverSingleNodeWithIncompatibleSeed() throws Exception {
    List<DiscoveryNode> knownNodes = new CopyOnWriteArrayList<>();
    try (MockTransportService seedTransport = startTransport("seed_node", knownNodes, Version.CURRENT);
        MockTransportService incomaptibleTransport = startTransport("incompat_seed_node", knownNodes, Version.fromString("2.0.0"));
        MockTransportService discoverableTransport = startTransport("discoverable_node", knownNodes, Version.CURRENT)) {
        DiscoveryNode seedNode = seedTransport.getLocalDiscoNode();
        DiscoveryNode discoverableNode = discoverableTransport.getLocalDiscoNode();
        DiscoveryNode incompatibleSeedNode = incomaptibleTransport.getLocalDiscoNode();
        knownNodes.add(seedTransport.getLocalDiscoNode());
        knownNodes.add(discoverableTransport.getLocalDiscoNode());
        knownNodes.add(incomaptibleTransport.getLocalDiscoNode());
        Collections.shuffle(knownNodes, random());
        List<DiscoveryNode> seedNodes = Arrays.asList(incompatibleSeedNode, 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)) {
                updateSeedNodes(connection, seedNodes);
                assertTrue(service.nodeConnected(seedNode));
                assertTrue(service.nodeConnected(discoverableNode));
                assertFalse(service.nodeConnected(incompatibleSeedNode));
                assertTrue(connection.assertNoRunningConnections());
            }
        }
    }
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 65 with CopyOnWriteArrayList

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

the class RemoteClusterConnectionTests method testFetchShards.

public void testFetchShards() throws Exception {
    List<DiscoveryNode> knownNodes = new CopyOnWriteArrayList<>();
    try (MockTransportService seedTransport = startTransport("seed_node", knownNodes, Version.CURRENT);
        MockTransportService discoverableTransport = startTransport("discoverable_node", knownNodes, Version.CURRENT)) {
        DiscoveryNode seedNode = seedTransport.getLocalDiscoNode();
        knownNodes.add(seedTransport.getLocalDiscoNode());
        knownNodes.add(discoverableTransport.getLocalDiscoNode());
        Collections.shuffle(knownNodes, 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", Arrays.asList(seedNode), service, Integer.MAX_VALUE, n -> true)) {
                if (randomBoolean()) {
                    updateSeedNodes(connection, Arrays.asList(seedNode));
                }
                SearchRequest request = new SearchRequest("test-index");
                CountDownLatch responseLatch = new CountDownLatch(1);
                AtomicReference<ClusterSearchShardsResponse> reference = new AtomicReference<>();
                AtomicReference<Exception> failReference = new AtomicReference<>();
                ActionListener<ClusterSearchShardsResponse> shardsListener = ActionListener.wrap(x -> {
                    reference.set(x);
                    responseLatch.countDown();
                }, x -> {
                    failReference.set(x);
                    responseLatch.countDown();
                });
                connection.fetchSearchShards(request, Arrays.asList("test-index"), shardsListener);
                responseLatch.await();
                assertNull(failReference.get());
                assertNotNull(reference.get());
                ClusterSearchShardsResponse clusterSearchShardsResponse = reference.get();
                assertEquals(knownNodes, Arrays.asList(clusterSearchShardsResponse.getNodes()));
                assertTrue(connection.assertNoRunningConnections());
            }
        }
    }
}
Also used : ClusterSearchShardsResponse(org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsResponse) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) 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) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Aggregations

CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)97 CountDownLatch (java.util.concurrent.CountDownLatch)38 IOException (java.io.IOException)23 ArrayList (java.util.ArrayList)23 List (java.util.List)23 Test (org.junit.Test)20 ExecutionException (java.util.concurrent.ExecutionException)15 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)13 CyclicBarrier (java.util.concurrent.CyclicBarrier)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)10 MockTransportService (org.elasticsearch.test.transport.MockTransportService)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 HashMap (java.util.HashMap)8 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 HashSet (java.util.HashSet)6 Map (java.util.Map)6 TimeUnit (java.util.concurrent.TimeUnit)6 Settings (org.elasticsearch.common.settings.Settings)6 Config (com.hazelcast.config.Config)5