• Home
    • View
    • Login
    This page
    • Normal
    • Export PDF
    • Export Word
    • Attachments
    • Page Information

    Loading...
  1. Dashboard
  2. Loom
  3. Main
  4. Getting started

Page History

Versions Compared

Old Version 32

changes.mady.by.user Alan Bateman

Saved on Jun 29, 2020

compared with

New Version Current

changes.mady.by.user Alan Bateman

Saved on yesterday at 3:24 PM

  • Previous Change: Difference between versions 31 and 32
  • View Page History

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, maybe waiting for a data to arrive on a network socket . Virtual threads are not suited to running code that is compute bound.In addition to to the Thread API, the or waiting for an element in queue for example.

Many applications won't use the Thread API directly but instead will use the java.util.concurrent.ExecutorService and Executors APIs are have . The Executors API has been updated to make it easy to work with virtual threadswith new factory methods for ExecutorServices that start a new thread for each task. Virtual threads are cheap enough that a new virtual thread can be created for each task, no need for pooling of there should never be a need to pool virtual threads.

Thread API

The following uses a static factory method to start a virtual thread. It invokes the join method to wait for the thread to terminate.

Code Block
languagejava
Thread thread = Thread.startVirtualThread(() -> System.out.println("Hello"));
thread.join();


The following is an example that creates a virtual thread that puts an element into a queue when it has completed a task. The main thread blocks on the queue, waiting for the element.

Code Block
languagejava
        var queue = new SynchronousQueue<String>();

        Thread.startVirtualThread(() -> {
            try {
                Thread.sleep(Duration.ofSeconds(2));
                queue.put("done");
            } catch (InterruptedException e) { }
        });

        String msg = queue.take();


The Thread.Builder API can also be used to create virtual threads that are configured at build time. The following has two code snippets. The first snippet below creates an un-started thread. The second snippet creates second creates and starts a thread with name "bob".

...

Code Block
languagejava
ThreadFactory factory = Thread.builder().virtual().name("worker", 0).factory();


Executors/ExecutorService API

The following creates example uses the Executors API to create an ExecutorService that runs starts a new virtual thread for each task in its own virtual thread. The example uses the try-with-resources construct to ensure that the ExecutorService has terminated before continuing.

ExecutorService defines submit methods to execute tasks for execution. The submit methods don't block, instead they return a Future object that the ExecutorService is shutdown and that the two tasks (each run in its own virtual thread) complete before continuing.can be used to wait for the result or exception. The submit method that takes a collection of tasks returns a Stream is lazily populated with completed Future objects representing the results.

The example also uses the invokeAll and invokeAny combinator methods to execute several tasks and wait them to complete.                                          

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

      executor.execute(() -> System.out.println("Hello"));      //  executor.execute(() -> System.out.println("Hi"));
}

The example below runs three tasks and selects the result of the first task to complete. The remaining tasks are cancelled, which causes the virtual threads running them to be interrupted.

Code Block
languagejava
try (ExecutorService executor = Executors.newVirtualThreadExecutor()) {Submits a value-returning task and waits for the result
            Callable<String>Future<String> task1future = executor.submit(() -> "foo");
    Callable<String> task2 = () -> "bar";   String result Callable<String> task3 = future.join() -> "baz";;

         String result = executor.invokeAny(List.of(task1, task2, task3));
}

This following example uses submitTasks to submit three value returning tasks. It uses the CompletableFuture.completed method to obtain a stream that is lazily populated as the tasks complete.

Code Block
languagejava
try (ExecutorService executor = Executors.newVirtualThreadExecutor()) { // Submits two value-returning tasks to get a Stream that is lazily populated
            // with completed Future objects as the tasks complete
            Callable<String>Stream<Future<String>> task1stream = executor.submit(List.of(() -> "foo";
    Callable<String> task2 = , () -> "bar"));
     Callable<String> task3 = () -> "baz";  stream.filter(Future::isCompletedNormally)
  List<CompletableFuture<String>> cfs = executor.submitTasks(List.of(task1, task2, task3));     CompletableFuture.completed(cfs)        .map(CompletableFutureFuture::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"));
}

The following creates an ExecutorService that runs each task in its own virtual thread with a deadline. If the deadline expires before the executor has terminated then the thread executing this code will be interrupted and any tasks running will be cancelled. (which causes the virtual thread to be interrupted).

Code Block
languagejava
Instant deadline = Instant.now().plusSeconds(30);
try (ExecutorService executor = Executors.newVirtualThreadExecutor().withDeadline(deadline)) {
    :

            // 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"));

        }



Overview
Content Tools
ThemeBuilder

Terms of Use • License: GPLv2 • Privacy • Trademarks • Contact Us

Powered by a free Atlassian Confluence Open Source Project License granted to https://www.atlassian.com/software/views/opensource-community-additional-license-offer. Evaluate Confluence today.

  • Adaptavist ThemeBuilder Powered by Atlassian Confluence 7.4.1
  • Adaptavist ThemeBuilder printed.by.atlassian.confluence
  • Report a bug
  • Atlassian News
Atlassian
Adaptavist ThemeBuilder EngineAtlassian Confluence
{"serverDuration": 515, "requestCorrelationId": "25de1c36f7ecaa6e"}