Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The easiest way to get started is to configure your IDE to use a recent Project Loom Early Access (EA) build and get familiar with using the java.lang.Thread API to create a virtual thread to execute some code. Virtual threads are just threads that are scheduled by the Java virtual machine rather than the operating system.  Virtual Virtual threads are best suited to executing code that spends most of its time blocked, waiting for a data to arrive on a network socket or waiting for an element in queue for example.

...

Code Block
languagejava
Thread thread1 = Thread.builder().virtual().task(() -> System.out.println("Hello")).build();

Thread thread2 = Thread.builder()
                       .virtual()
                       .name("bobscrooge")
                       .task(() -> System.out.println("I'm Bob!"))
                       .start();

...

Code Block
languagejava
        try (ExecutorService executor = Executors.newVirtualThreadExecutor()) {

            // Submits a value-returning task and waits for the result
            Future<String> future = executor.submit(() -> "foo");
            String result = future.join();

            // Submits two value-returning tasks to get a Stream that is lazily populated
            // with completed Future objects as the tasks complete
            Stream<Future<String>> stream = executor.submit(List.of(() -> "foo", () -> "bar"));
            stream.filter(Future::isCompletedNormally)
                    .map(Future::join)
                    .forEach(System.out::println);

            // Executes two value-returning tasks, waiting for both to complete
            List<Future<String>> results1 = executor.invokeAll(List.of(() -> "foo", () -> "bar"));

            // Executes two value-returning tasks, waiting for both to complete. If one of the
            // tasks completes with an exception, the other is cancelled.
            List<Future<String>> results2 = executor.invokeAll(List.of(() -> "foo", () -> "bar"), /*cancelOnException*/ true);

            // Executes two value-returning tasks, returning the result of the first to
            // complete, cancelling the other.
            String first = executor.invokeAny(List.of(() -> "foo", () -> "bar"));

        }

...