io.vertx.core.WorkerExecutor Java Examples

The following examples show how to use io.vertx.core.WorkerExecutor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VertxCompletableFuture.java    From vertx-completable-future with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a action running in the provided
 * Vert.x worker thread pool.
 * <p>
 * This method is different from {@link CompletableFuture#runAsync(Runnable)} as it does not use a fork join
 * executor, but the provided worker thread pool.
 *
 * @param context  the Vert.x context
 * @param worker   the WorkerExecution on which the runnable is to be executed
 * @param runnable the action, when its execution completes, it completes the returned CompletableFuture. If the
 *                 execution throws an exception, the returned CompletableFuture is completed exceptionally.
 * @return the new CompletableFuture
 */
public static VertxCompletableFuture<Void> runBlockingAsyncOn(Context context, WorkerExecutor worker, Runnable runnable) {
  Objects.requireNonNull(runnable);
  VertxCompletableFuture<Void> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
  Objects.requireNonNull(worker).<Void>executeBlocking(
      fut -> {
        try {
          runnable.run();
          fut.complete(null);
        } catch (Throwable e) {
          fut.fail(e);
        }
      },
      false,
      ar -> {
        if (ar.failed()) {
          future.completeExceptionally(ar.cause());
        } else {
          future.complete(ar.result());
        }
      }
  );
  return future;
}
 
Example #2
Source File: VertxCompletableFuture.java    From vertx-completable-future with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the provided
 * Vert.x worker thread pool.
 * <p>
 * This method is different from {@link CompletableFuture#supplyAsync(Supplier)} as it does not use a fork join
 * executor, but the worker thread pool.
 *
 * @param context  the context in which the supplier is executed.
 * @param worker   the WorkerExecution on which the supplier is to be executed
 * @param supplier a function returning the value to be used to complete the returned CompletableFuture
 * @param <T>      the function's return type
 * @return the new CompletableFuture
 */
public static <T> VertxCompletableFuture<T> supplyBlockingAsyncOn(Context context, WorkerExecutor worker, Supplier<T> supplier) {
  Objects.requireNonNull(supplier);
  VertxCompletableFuture<T> future = new VertxCompletableFuture<>(context);
  Objects.requireNonNull(worker).<T>executeBlocking(
          fut -> {
            try {
              fut.complete(supplier.get());
            } catch (Throwable e) {
              fut.fail(e);
            }
          },
          false,
          ar -> {
            if (ar.failed()) {
              future.completeExceptionally(ar.cause());
            } else {
              future.complete(ar.result());
            }
          }
  );
  return future;
}
 
Example #3
Source File: DefaultCompletableAsyncResult.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
@Override
public <U> AsyncResult<U> thenScheduleBlockingApply(WorkerExecutor executor, Function<? super T, ? extends U> fn) {
  requireNonNull(executor);
  requireNonNull(fn);
  CompletableAsyncResult<U> asyncResult = AsyncResult.incomplete();
  future.whenComplete((t, ex1) -> {
    if (ex1 == null) {
      try {
        executor.<U>executeBlocking(vertxFuture -> vertxFuture.complete(fn.apply(t)), false, res -> {
          if (res.succeeded()) {
            asyncResult.complete(res.result());
          } else {
            asyncResult.completeExceptionally(res.cause());
          }
        });
      } catch (Throwable ex2) {
        asyncResult.completeExceptionally(ex2);
      }
    } else {
      asyncResult.completeExceptionally(ex1);
    }
  });
  return asyncResult;
}
 
Example #4
Source File: AsyncCompletion.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a completion that completes after the given blocking action executes asynchronously on a vertx executor.
 *
 * @param executor A vertx executor.
 * @param action The blocking action to execute.
 * @return A completion.
 */
static AsyncCompletion executeBlocking(WorkerExecutor executor, Runnable action) {
  requireNonNull(action);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  executor.executeBlocking(future -> {
    action.run();
    future.complete();
  }, false, res -> {
    if (res.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(res.cause());
    }
  });
  return completion;
}
 
Example #5
Source File: DefaultCompletableAsyncResult.java    From cava with Apache License 2.0 6 votes vote down vote up
@Override
public <U> AsyncResult<U> thenScheduleBlockingApply(WorkerExecutor executor, Function<? super T, ? extends U> fn) {
  requireNonNull(executor);
  requireNonNull(fn);
  CompletableAsyncResult<U> asyncResult = AsyncResult.incomplete();
  future.whenComplete((t, ex1) -> {
    if (ex1 == null) {
      try {
        executor.<U>executeBlocking(vertxFuture -> vertxFuture.complete(fn.apply(t)), false, res -> {
          if (res.succeeded()) {
            asyncResult.complete(res.result());
          } else {
            asyncResult.completeExceptionally(res.cause());
          }
        });
      } catch (Throwable ex2) {
        asyncResult.completeExceptionally(ex2);
      }
    } else {
      asyncResult.completeExceptionally(ex1);
    }
  });
  return asyncResult;
}
 
Example #6
Source File: AsyncCompletion.java    From cava with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a completion that completes after the given blocking action executes asynchronously on a vertx executor.
 *
 * @param executor A vertx executor.
 * @param action The blocking action to execute.
 * @return A completion.
 */
static AsyncCompletion executeBlocking(WorkerExecutor executor, Runnable action) {
  requireNonNull(action);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  executor.executeBlocking(future -> {
    action.run();
    future.complete();
  }, false, res -> {
    if (res.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(res.cause());
    }
  });
  return completion;
}
 
Example #7
Source File: AsyncResult.java    From cava with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a result that, after the given blocking function executes asynchronously on a vertx executor and returns a
 * result, completes when the returned result completes, with the same value or exception.
 *
 * @param executor A vertx executor.
 * @param fn The function returning a result.
 * @param <T> The type of the returned result's value.
 * @return A new result.
 */
static <T> AsyncResult<T> executeBlocking(WorkerExecutor executor, Supplier<T> fn) {
  requireNonNull(fn);
  CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete();
  executor.<T>executeBlocking(future -> future.complete(fn.get()), false, res -> {
    if (res.succeeded()) {
      asyncResult.complete(res.result());
    } else {
      asyncResult.completeExceptionally(res.cause());
    }
  });
  return asyncResult;
}
 
Example #8
Source File: SupplyAndRunAsyncTest.java    From vertx-completable-future with Apache License 2.0 5 votes vote down vote up
@Test
public void testSupplyBlockingAsyncOn() throws ExecutionException, InterruptedException {
  String threadPoolName = "testing-thread-pool";
  WorkerExecutor worker = vertx.createSharedWorkerExecutor(threadPoolName);
  CompletableFuture<String> future = VertxCompletableFuture.supplyBlockingAsyncOn(vertx, worker, () ->
      Thread.currentThread().getName());
  String s = future.get();
  Assert.assertTrue(s.contains(threadPoolName));
}
 
Example #9
Source File: OutboundEndpointTest.java    From vertx-camel-bridge with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithBlockingWithWorker() throws Exception {
  AtomicBoolean calledSpy = new AtomicBoolean();
  AtomicBoolean startedSpy = new AtomicBoolean();
  vertx.createHttpServer().requestHandler(request -> {
    calledSpy.set(true);
    request.response().end("Alright");
  }).listen(8081, ar -> {
    startedSpy.set(ar.succeeded());
  });

  await().atMost(DEFAULT_TIMEOUT).untilAtomic(startedSpy, is(true));

  camel.addRoutes(new RouteBuilder() {
    @Override
    public void configure() throws Exception {
      from("direct:my-route")
        .process(exchange -> Thread.sleep(3000))
        .to("http://localhost:8081");
    }
  });

  WorkerExecutor pool = vertx.createSharedWorkerExecutor("some-fancy-name");

  bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel)
    .addOutboundMapping(fromVertx("camel-route").toCamel("direct:my-route").setBlocking(true)
      .setWorkerExecutor(pool)));

  camel.start();
  BridgeHelper.startBlocking(bridge);

  vertx.eventBus().send("camel-route", "hello");

  await().atMost(DEFAULT_TIMEOUT).untilAtomic(calledSpy, is(true));
}
 
Example #10
Source File: SupplyAndRunAsyncTest.java    From vertx-completable-future with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunBlockingAsyncOn() throws ExecutionException, InterruptedException {
  String threadPoolName = "testing-thread-pool";
  WorkerExecutor worker = vertx.createSharedWorkerExecutor(threadPoolName);
  AtomicReference<String> reference = new AtomicReference<>();
  CompletableFuture<Void> future = VertxCompletableFuture.runBlockingAsyncOn(vertx, worker, () ->
      reference.set(Thread.currentThread().getName()));
  future.get();
  Assert.assertTrue(reference.get().contains(threadPoolName));
}
 
Example #11
Source File: ContextScheduler.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public ContextScheduler(WorkerExecutor workerExecutor, boolean ordered) {
  Objects.requireNonNull(workerExecutor, "workerExecutor is null");
  this.vertx = ((WorkerExecutorInternal) workerExecutor).vertx();
  this.context = null;
  this.workerExecutor = workerExecutor;
  this.blocking = true;
  this.ordered = ordered;
}
 
Example #12
Source File: DefaultCompletableAsyncCompletion.java    From cava with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncCompletion thenScheduleBlockingRun(WorkerExecutor executor, Runnable runnable) {
  requireNonNull(executor);
  requireNonNull(runnable);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  future.whenComplete((t, ex1) -> {
    if (ex1 == null) {
      try {
        executor.executeBlocking(vertxFuture -> {
          runnable.run();
          vertxFuture.complete(null);
        }, false, res -> {
          if (res.succeeded()) {
            completion.complete();
          } else {
            completion.completeExceptionally(res.cause());
          }
        });
      } catch (Throwable ex2) {
        completion.completeExceptionally(ex2);
      }
    } else {
      completion.completeExceptionally(ex1);
    }
  });
  return completion;
}
 
Example #13
Source File: DefaultCompletableAsyncResult.java    From cava with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncCompletion thenScheduleBlockingRun(WorkerExecutor executor, Runnable runnable) {
  requireNonNull(executor);
  requireNonNull(runnable);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  future.whenComplete((t, ex1) -> {
    if (ex1 == null) {
      try {
        executor.executeBlocking(vertxFuture -> {
          runnable.run();
          vertxFuture.complete(null);
        }, false, res -> {
          if (res.succeeded()) {
            completion.complete();
          } else {
            completion.completeExceptionally(res.cause());
          }
        });
      } catch (Throwable ex2) {
        completion.completeExceptionally(ex2);
      }
    } else {
      completion.completeExceptionally(ex1);
    }
  });
  return completion;
}
 
Example #14
Source File: ContextScheduler.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public ContextScheduler(WorkerExecutor workerExecutor, boolean ordered) {
  Objects.requireNonNull(workerExecutor, "workerExecutor is null");
  this.vertx = ((WorkerExecutorInternal) workerExecutor).vertx();
  this.context = null;
  this.workerExecutor = workerExecutor;
  this.blocking = true;
  this.ordered = ordered;
}
 
Example #15
Source File: AsyncResult.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a result that, after the given blocking function executes asynchronously on a vertx executor and returns a
 * result, completes when the returned result completes, with the same value or exception.
 *
 * @param executor A vertx executor.
 * @param fn The function returning a result.
 * @param <T> The type of the returned result's value.
 * @return A new result.
 */
static <T> AsyncResult<T> executeBlocking(WorkerExecutor executor, Supplier<T> fn) {
  requireNonNull(fn);
  CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete();
  executor.<T>executeBlocking(future -> future.complete(fn.get()), false, res -> {
    if (res.succeeded()) {
      asyncResult.complete(res.result());
    } else {
      asyncResult.completeExceptionally(res.cause());
    }
  });
  return asyncResult;
}
 
Example #16
Source File: DatabaseProviderVertx.java    From database with Apache License 2.0 5 votes vote down vote up
private BuilderImpl(WorkerExecutor executor, Closeable pool, Supplier<Connection> connectionProvider,
                    Options options) {
  this.executor = executor;
  this.pool = pool;
  this.connectionProvider = connectionProvider;
  this.options = options;
}
 
Example #17
Source File: DefaultCompletableAsyncResult.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncCompletion thenScheduleBlockingRun(WorkerExecutor executor, Runnable runnable) {
  requireNonNull(executor);
  requireNonNull(runnable);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  future.whenComplete((t, ex1) -> {
    if (ex1 == null) {
      try {
        executor.executeBlocking(vertxFuture -> {
          runnable.run();
          vertxFuture.complete(null);
        }, false, res -> {
          if (res.succeeded()) {
            completion.complete();
          } else {
            completion.completeExceptionally(res.cause());
          }
        });
      } catch (Throwable ex2) {
        completion.completeExceptionally(ex2);
      }
    } else {
      completion.completeExceptionally(ex1);
    }
  });
  return completion;
}
 
Example #18
Source File: DefaultCompletableAsyncCompletion.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncCompletion thenScheduleBlockingRun(WorkerExecutor executor, Runnable runnable) {
  requireNonNull(executor);
  requireNonNull(runnable);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  future.whenComplete((t, ex1) -> {
    if (ex1 == null) {
      try {
        executor.executeBlocking(vertxFuture -> {
          runnable.run();
          vertxFuture.complete(null);
        }, false, res -> {
          if (res.succeeded()) {
            completion.complete();
          } else {
            completion.completeExceptionally(res.cause());
          }
        });
      } catch (Throwable ex2) {
        completion.completeExceptionally(ex2);
      }
    } else {
      completion.completeExceptionally(ex1);
    }
  });
  return completion;
}
 
Example #19
Source File: DefaultCompletableAsyncCompletionTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void testRunOnWorker(@VertxInstance Vertx vertx) throws InterruptedException {
  AtomicReference<Boolean> executed = new AtomicReference<>();
  WorkerExecutor executor = vertx.createSharedWorkerExecutor("foo");
  AsyncCompletion completion = AsyncCompletion.executeBlocking(executor, () -> executed.set(true));
  completion.join();
  assertTrue(executed.get());
}
 
Example #20
Source File: DatabaseProviderVertx.java    From database with Apache License 2.0 5 votes vote down vote up
public DatabaseProviderVertx(WorkerExecutor executor, Supplier<Connection> connectionProvider, Options options) {
  if (executor == null) {
    throw new IllegalArgumentException("Worker executor cannot be null");
  }
  if (connectionProvider == null) {
    throw new IllegalArgumentException("Connection provider cannot be null");
  }
  this.executor = executor;
  this.connectionProvider = connectionProvider;
  this.options = options;
}
 
Example #21
Source File: DefaultCompletableAsyncResultTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void thenScheduleBlockingRunWithWorker(@VertxInstance Vertx vertx) throws Exception {
  CompletableAsyncResult<String> asyncResult = AsyncResult.incomplete();
  AtomicReference<Boolean> ref = new AtomicReference<>();
  WorkerExecutor executor = vertx.createSharedWorkerExecutor("foo");
  AsyncCompletion completion = asyncResult.thenScheduleBlockingRun(executor, () -> ref.set(true));
  asyncResult.complete("Completed1");
  completion.join();
  assertThat(ref.get()).isTrue();
}
 
Example #22
Source File: DefaultCompletableAsyncResultTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void thenScheduleBlockingApplyWorker(@VertxInstance Vertx vertx) throws Exception {
  CompletableAsyncResult<String> asyncResult = AsyncResult.incomplete();
  WorkerExecutor executor = vertx.createSharedWorkerExecutor("foo");
  AsyncResult<String> completion = asyncResult.thenScheduleBlockingApply(executor, (value) -> value + "foo");
  asyncResult.complete("Completed1");
  assertThat(completion.get()).isEqualTo("Completed1foo");
}
 
Example #23
Source File: DefaultCompletableAsyncResultTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void testRunOnWorker(@VertxInstance Vertx vertx) throws InterruptedException {
  AtomicReference<Boolean> executed = new AtomicReference<>();
  WorkerExecutor executor = vertx.createSharedWorkerExecutor("foo");
  AsyncResult<String> result = AsyncResult.executeBlocking(executor, () -> "foo");
  assertEquals("foo", result.get());
}
 
Example #24
Source File: DefaultCompletableAsyncCompletionTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void thenScheduleBlockingRunWithWorker(@VertxInstance Vertx vertx) throws Exception {
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  AtomicReference<Boolean> ref = new AtomicReference<>();
  WorkerExecutor executor = vertx.createSharedWorkerExecutor("foo");
  AsyncCompletion after = completion.thenScheduleBlockingRun(executor, () -> ref.set(true));
  completion.complete();
  after.join();
  assertThat(ref.get()).isTrue();
}
 
Example #25
Source File: VertxPoolMetricsTest.java    From vertx-micrometer-metrics with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldReportNamedPoolMetrics(TestContext context) throws InterruptedException {
  int maxPoolSize = 8;
  int taskCount = maxPoolSize * 3;
  int sleepMillis = 30;

  vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions()
    .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
    .addLabels(Label.POOL_NAME)
    .setEnabled(true)))
    .exceptionHandler(context.exceptionHandler());

  // Setup executor
  WorkerExecutor workerExecutor = vertx.createSharedWorkerExecutor("test-worker", maxPoolSize);
  Async ready = context.async(taskCount);
  for (int i = 0; i < taskCount; i++) {
    workerExecutor.executeBlocking(future -> {
      try {
        Thread.sleep(sleepMillis);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      future.complete();
    }, false, context.asyncAssertSuccess(v -> {
      ready.countDown();
    }));
  }
  ready.awaitSuccess();
  RegistryInspector.waitForValue(
    vertx,
    context,
    "vertx.pool.completed[pool_name=test-worker,pool_type=worker]$COUNT",
    value -> value.intValue() == taskCount);

  List<RegistryInspector.Datapoint> datapoints = listDatapoints(startsWith("vertx.pool"));
  assertThat(datapoints).hasSize(10).contains(
    dp("vertx.pool.queue.size[pool_name=test-worker,pool_type=worker]$VALUE", 0),
    dp("vertx.pool.inUse[pool_name=test-worker,pool_type=worker]$VALUE", 0),
    dp("vertx.pool.ratio[pool_name=test-worker,pool_type=worker]$VALUE", 0),
    dp("vertx.pool.completed[pool_name=test-worker,pool_type=worker]$COUNT", taskCount),
    dp("vertx.pool.queue.delay[pool_name=test-worker,pool_type=worker]$COUNT", taskCount),
    dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$COUNT", taskCount));

  assertThat(datapoints)
    .usingFieldByFieldElementComparator()
    .usingComparatorForElementFieldsWithType(new DoubleComparator(0.1), Double.class)
    .contains(dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$MAX", sleepMillis / 1000d));

  class GreaterOrEqualsComparator implements Comparator<Double> {
    @Override
    public int compare(Double o1, Double o2) {
      return o1 < o2 ? -1 : 0;
    }
  }

  assertThat(datapoints)
    .usingFieldByFieldElementComparator()
    .usingComparatorForElementFieldsWithType(new GreaterOrEqualsComparator(), Double.class)
    .contains(
      dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$TOTAL_TIME", taskCount * sleepMillis / 1000d));
}
 
Example #26
Source File: ContextScheduler.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
public ContextScheduler(WorkerExecutor workerExecutor) {
  this(workerExecutor, true);
}
 
Example #27
Source File: VertxUtil.java    From database with Apache License 2.0 4 votes vote down vote up
/**
 * Equivalent to {@link Vertx#executeBlocking(Handler, boolean, Handler)},
 * but preserves the {@link MDC} correctly.
 */
public static <T> void executeBlocking(WorkerExecutor executor, Handler<Future<T>> future, boolean ordered,
                                       Handler<AsyncResult<T>> handler) {
  executor.executeBlocking(mdc(future), ordered, mdcEventLoop(handler));
}
 
Example #28
Source File: ContextScheduler.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
public ContextScheduler(WorkerExecutor workerExecutor) {
  this(workerExecutor, true);
}
 
Example #29
Source File: SfsVertxImpl.java    From sfs with Apache License 2.0 4 votes vote down vote up
@Override
public WorkerExecutor createSharedWorkerExecutor(String name) {
    return vertx.createSharedWorkerExecutor(name);
}
 
Example #30
Source File: SfsVertxImpl.java    From sfs with Apache License 2.0 4 votes vote down vote up
@Override
public WorkerExecutor createSharedWorkerExecutor(String name, int poolSize) {
    return vertx.createSharedWorkerExecutor(name, poolSize);
}