4

Say I have this:

  private static ExecutorService executor = Executors.newFixedThreadPool(1);

  executor.execute(() -> {
     Thread.sleep(100);
      doSomething();
  });

since I am reusing a thread, I am blocking it if others want to use the thread. My question is - is there a way to simply register a callback, something like this:

   executor.execute(() -> {
        timers.setTimeout(() -> {  // imaginary utility
             doSomething();
        },100);
   });

is this possible with core Java?

8
  • 6
    I think you want CompletableFutures Commented Feb 4, 2019 at 23:55
  • I wonder if there is any relationship between CompletableFuture and the Future class in vertx Commented Feb 5, 2019 at 0:03
  • 1
    It’s unlikely - while Vert.x uses the JVM as a runtime environment, it doesn’t appear to borrow any of Java’s runtime libraries Commented Feb 5, 2019 at 0:06
  • @MTCoster yeah my primary fear is that CompletableFutures that don't access an event loop are just using Thread.sleep under the hood or something Commented Feb 5, 2019 at 0:15
  • Why does it matter whether it uses Thread.sleep()? The call to execute() returns immediately, so your main thread will continue to be responsive Commented Feb 5, 2019 at 0:17

1 Answer 1

3

Yeah it looks like this works fine, I tested it on Java 10:

CompletableFuture.delayedExecutor(1, TimeUnit.MILLISECONDS).execute(() -> {
    doSomething();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.