Search in sources :

Example 41 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project crate by crate.

the class RepositoryService method execute.

public CompletableFuture<Long> execute(DropRepositoryAnalyzedStatement analyzedStatement) {
    final CompletableFuture<Long> future = new CompletableFuture<>();
    final String repoName = analyzedStatement.repositoryName();
    deleteRepositoryAction.execute(new DeleteRepositoryRequest(repoName), new ActionListener<DeleteRepositoryResponse>() {

        @Override
        public void onResponse(DeleteRepositoryResponse deleteRepositoryResponse) {
            if (!deleteRepositoryResponse.isAcknowledged()) {
                LOGGER.info("delete repository '{}' not acknowledged", repoName);
            }
            future.complete(1L);
        }

        @Override
        public void onFailure(Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) DeleteRepositoryResponse(org.elasticsearch.action.admin.cluster.repositories.delete.DeleteRepositoryResponse) DeleteRepositoryRequest(org.elasticsearch.action.admin.cluster.repositories.delete.DeleteRepositoryRequest)

Example 42 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project vert.x by eclipse.

the class HttpMetricsTest method testHttpClientLifecycle.

private void testHttpClientLifecycle(HttpVersion protocol) throws Exception {
    HttpServer server = vertx.createHttpServer();
    CountDownLatch requestBeginLatch = new CountDownLatch(1);
    CountDownLatch requestBodyLatch = new CountDownLatch(1);
    CountDownLatch requestEndLatch = new CountDownLatch(1);
    CompletableFuture<Void> beginResponse = new CompletableFuture<>();
    CompletableFuture<Void> endResponse = new CompletableFuture<>();
    server.requestHandler(req -> {
        assertEquals(protocol, req.version());
        requestBeginLatch.countDown();
        req.handler(buff -> {
            requestBodyLatch.countDown();
        });
        req.endHandler(v -> {
            requestEndLatch.countDown();
        });
        Context ctx = vertx.getOrCreateContext();
        beginResponse.thenAccept(v1 -> {
            ctx.runOnContext(v2 -> {
                req.response().setChunked(true).write(TestUtils.randomAlphaString(1024));
            });
        });
        endResponse.thenAccept(v1 -> {
            ctx.runOnContext(v2 -> {
                req.response().end();
            });
        });
    });
    CountDownLatch listenLatch = new CountDownLatch(1);
    server.listen(8080, "localhost", onSuccess(s -> {
        listenLatch.countDown();
    }));
    awaitLatch(listenLatch);
    HttpClient client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(protocol));
    FakeHttpClientMetrics clientMetrics = FakeMetricsBase.getMetrics(client);
    CountDownLatch responseBeginLatch = new CountDownLatch(1);
    CountDownLatch responseEndLatch = new CountDownLatch(1);
    HttpClientRequest req = client.post(8080, "localhost", "/somepath", resp -> {
        responseBeginLatch.countDown();
        resp.endHandler(v -> {
            responseEndLatch.countDown();
        });
    }).setChunked(true);
    req.sendHead();
    awaitLatch(requestBeginLatch);
    HttpClientMetric reqMetric = clientMetrics.getMetric(req);
    assertEquals(0, reqMetric.requestEnded.get());
    assertEquals(0, reqMetric.responseBegin.get());
    req.write(TestUtils.randomAlphaString(1024));
    awaitLatch(requestBodyLatch);
    assertEquals(0, reqMetric.requestEnded.get());
    assertEquals(0, reqMetric.responseBegin.get());
    req.end();
    awaitLatch(requestEndLatch);
    assertEquals(1, reqMetric.requestEnded.get());
    assertEquals(0, reqMetric.responseBegin.get());
    beginResponse.complete(null);
    awaitLatch(responseBeginLatch);
    assertEquals(1, reqMetric.requestEnded.get());
    assertEquals(1, reqMetric.responseBegin.get());
    endResponse.complete(null);
    awaitLatch(responseEndLatch);
    assertNull(clientMetrics.getMetric(req));
    assertEquals(1, reqMetric.requestEnded.get());
    assertEquals(1, reqMetric.responseBegin.get());
}
Also used : Context(io.vertx.core.Context) FakeMetricsBase(io.vertx.test.fakemetrics.FakeMetricsBase) FakeMetricsFactory(io.vertx.test.fakemetrics.FakeMetricsFactory) HttpServerMetric(io.vertx.test.fakemetrics.HttpServerMetric) HttpServer(io.vertx.core.http.HttpServer) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpClientRequest(io.vertx.core.http.HttpClientRequest) FakeHttpServerMetrics(io.vertx.test.fakemetrics.FakeHttpServerMetrics) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) MetricsOptions(io.vertx.core.metrics.MetricsOptions) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpClientMetric(io.vertx.test.fakemetrics.HttpClientMetric) HttpClient(io.vertx.core.http.HttpClient) FakeHttpClientMetrics(io.vertx.test.fakemetrics.FakeHttpClientMetrics) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient) HttpServer(io.vertx.core.http.HttpServer) FakeHttpClientMetrics(io.vertx.test.fakemetrics.FakeHttpClientMetrics) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpClientMetric(io.vertx.test.fakemetrics.HttpClientMetric)

Example 43 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project vert.x by eclipse.

the class HttpTest method testDeliverPausedBufferWhenResume.

@Test
public void testDeliverPausedBufferWhenResume() throws Exception {
    Buffer data = TestUtils.randomBuffer(20);
    int num = 10;
    waitFor(num);
    List<CompletableFuture<Void>> resumes = Collections.synchronizedList(new ArrayList<>());
    for (int i = 0; i < num; i++) {
        resumes.add(new CompletableFuture<>());
    }
    server.requestHandler(req -> {
        int idx = Integer.parseInt(req.path().substring(1));
        HttpServerResponse resp = req.response();
        resumes.get(idx).thenAccept(v -> {
            resp.end();
        });
        resp.setChunked(true).write(data);
    });
    startServer();
    client.close();
    client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1).setKeepAlive(true));
    for (int i = 0; i < num; i++) {
        int idx = i;
        client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/" + i, resp -> {
            Buffer body = Buffer.buffer();
            resp.handler(buff -> {
                resumes.get(idx).complete(null);
                body.appendBuffer(buff);
            });
            resp.endHandler(v -> {
                assertEquals(data, body);
                complete();
            });
            resp.pause();
            vertx.setTimer(10, id -> {
                resp.resume();
            });
        }).end();
    }
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) VertxException(io.vertx.core.VertxException) MultiMap(io.vertx.core.MultiMap) TimeoutException(java.util.concurrent.TimeoutException) Context(io.vertx.core.Context) InetAddress(java.net.InetAddress) HttpFrame(io.vertx.core.http.HttpFrame) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) HttpHeaders(io.vertx.core.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) UUID(java.util.UUID) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) Nullable(io.vertx.codegen.annotations.Nullable) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) AbstractVerticle(io.vertx.core.AbstractVerticle) WorkerContext(io.vertx.core.impl.WorkerContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) IntStream(java.util.stream.IntStream) HeadersAdaptor(io.vertx.core.http.impl.HeadersAdaptor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) OutputStreamWriter(java.io.OutputStreamWriter) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) BufferedWriter(java.io.BufferedWriter) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) EventLoopContext(io.vertx.core.impl.EventLoopContext) URLEncoder(java.net.URLEncoder) Rule(org.junit.Rule) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) TemporaryFolder(org.junit.rules.TemporaryFolder) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) CompletableFuture(java.util.concurrent.CompletableFuture) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Test(org.junit.Test)

Example 44 with CompletableFuture

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

the class Cache method computeIfAbsent.

/**
     * If the specified key is not already associated with a value (or is mapped to null), attempts to compute its
     * value using the given mapping function and enters it into this map unless null. The load method for a given key
     * will be invoked at most once.
     *
     * Use of different {@link CacheLoader} implementations on the same key concurrently may result in only the first
     * loader function being called and the second will be returned the result provided by the first including any exceptions
     * thrown during the execution of the first.
     *
     * @param key    the key whose associated value is to be returned or computed for if non-existent
     * @param loader the function to compute a value given a key
     * @return the current (existing or computed) non-null value associated with the specified key
     * @throws ExecutionException thrown if loader throws an exception or returns a null value
     */
public V computeIfAbsent(K key, CacheLoader<K, V> loader) throws ExecutionException {
    long now = now();
    V value = get(key, now);
    if (value == null) {
        // we need to synchronize loading of a value for a given key; however, holding the segment lock while
        // invoking load can lead to deadlock against another thread due to dependent key loading; therefore, we
        // need a mechanism to ensure that load is invoked at most once, but we are not invoking load while holding
        // the segment lock; to do this, we atomically put a future in the map that can load the value, and then
        // get the value from this future on the thread that won the race to place the future into the segment map
        CacheSegment<K, V> segment = getCacheSegment(key);
        CompletableFuture<Entry<K, V>> future;
        CompletableFuture<Entry<K, V>> completableFuture = new CompletableFuture<>();
        try (ReleasableLock ignored = segment.writeLock.acquire()) {
            future = segment.map.putIfAbsent(key, completableFuture);
        }
        BiFunction<? super Entry<K, V>, Throwable, ? extends V> handler = (ok, ex) -> {
            if (ok != null) {
                try (ReleasableLock ignored = lruLock.acquire()) {
                    promote(ok, now);
                }
                return ok.value;
            } else {
                try (ReleasableLock ignored = segment.writeLock.acquire()) {
                    CompletableFuture<Entry<K, V>> sanity = segment.map.get(key);
                    if (sanity != null && sanity.isCompletedExceptionally()) {
                        segment.map.remove(key);
                    }
                }
                return null;
            }
        };
        CompletableFuture<V> completableValue;
        if (future == null) {
            future = completableFuture;
            completableValue = future.handle(handler);
            V loaded;
            try {
                loaded = loader.load(key);
            } catch (Exception e) {
                future.completeExceptionally(e);
                throw new ExecutionException(e);
            }
            if (loaded == null) {
                NullPointerException npe = new NullPointerException("loader returned a null value");
                future.completeExceptionally(npe);
                throw new ExecutionException(npe);
            } else {
                future.complete(new Entry<>(key, loaded, now));
            }
        } else {
            completableValue = future.handle(handler);
        }
        try {
            value = completableValue.get();
            // check to ensure the future hasn't been completed with an exception
            if (future.isCompletedExceptionally()) {
                // call get to force the exception to be thrown for other concurrent callers
                future.get();
                throw new IllegalStateException("the future was completed exceptionally but no exception was thrown");
            }
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
    return value;
}
Also used : LongAdder(java.util.concurrent.atomic.LongAdder) ReleasableLock(org.elasticsearch.common.util.concurrent.ReleasableLock) Arrays(java.util.Arrays) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) BiFunction(java.util.function.BiFunction) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Objects(java.util.Objects) ExecutionException(java.util.concurrent.ExecutionException) ToLongBiFunction(java.util.function.ToLongBiFunction) Map(java.util.Map) Tuple(org.elasticsearch.common.collect.Tuple) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ReleasableLock(org.elasticsearch.common.util.concurrent.ReleasableLock) ExecutionException(java.util.concurrent.ExecutionException) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionException(java.util.concurrent.ExecutionException)

Example 45 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project vert.x by eclipse.

the class NamedWorkerPoolTest method testDestroyWorkerPoolWhenVerticleUndeploys.

@Test
public void testDestroyWorkerPoolWhenVerticleUndeploys() throws Exception {
    String poolName = "vert.x-" + TestUtils.randomAlphaString(10);
    AtomicReference<Thread> thread = new AtomicReference<>();
    CompletableFuture<String> deploymentIdRef = new CompletableFuture<>();
    vertx.deployVerticle(new AbstractVerticle() {

        @Override
        public void start() throws Exception {
            WorkerExecutor pool = vertx.createSharedWorkerExecutor(poolName);
            pool.executeBlocking(fut -> {
                thread.set(Thread.currentThread());
            }, ar -> {
            });
        }
    }, onSuccess(deploymentIdRef::complete));
    waitUntil(() -> thread.get() != null);
    String deploymentId = deploymentIdRef.get(20, TimeUnit.SECONDS);
    vertx.undeploy(deploymentId, onSuccess(v -> {
    }));
    waitUntil(() -> thread.get().getState() == Thread.State.TERMINATED);
}
Also used : Vertx(io.vertx.core.Vertx) Set(java.util.Set) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) WorkerExecutor(io.vertx.core.WorkerExecutor) HashSet(java.util.HashSet) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) DeploymentOptions(io.vertx.core.DeploymentOptions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractVerticle(io.vertx.core.AbstractVerticle) Collections(java.util.Collections) CompletableFuture(java.util.concurrent.CompletableFuture) WorkerExecutor(io.vertx.core.WorkerExecutor) AtomicReference(java.util.concurrent.atomic.AtomicReference) AbstractVerticle(io.vertx.core.AbstractVerticle) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Test(org.junit.Test)

Aggregations

CompletableFuture (java.util.concurrent.CompletableFuture)490 Test (org.junit.Test)152 ArrayList (java.util.ArrayList)88 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)77 List (java.util.List)75 UUID (java.util.UUID)62 Futures (io.pravega.common.concurrent.Futures)60 Map (java.util.Map)59 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)57 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)53 HashMap (java.util.HashMap)52 TimeUnit (java.util.concurrent.TimeUnit)52 Cleanup (lombok.Cleanup)49 Exceptions (io.pravega.common.Exceptions)48 Collectors (java.util.stream.Collectors)48 lombok.val (lombok.val)47 IOException (java.io.IOException)46 Duration (java.time.Duration)46 Slf4j (lombok.extern.slf4j.Slf4j)46 AtomicReference (java.util.concurrent.atomic.AtomicReference)45