当前位置:网站首页>Create a virtual thread using loom - David

Create a virtual thread using loom - David

2022-06-12 22:05:00 Solution jdon

In this article , We show how to use Loom The implementation is similar to Go Green virtual thread of language .

Project loom Still in preview , It means api May change at any time . If you want to try these examples yourself , You can use Early-access build 19-loom+4-115 (2022/2/13) To make the .

 

Introducing virtual threads

Java Threads in are just a little wrapper around threads that are managed and scheduled by the operating system .Project Loom towards Java Added a new thread called virtual thread , These threads are composed of JVM Management and scheduling .

To create a platform thread ( Threads managed by the operating system ), You need to make a system call , And these calls are expensive . To create a virtual thread , You don't have to make any system calls , This allows these threads to be made cheaply when you need them . These virtual threads run on the carrier thread . Behind the scenes ,JVM Some platform threads are created for virtual threads to run . Because we don't have system calls and context switches , We can run thousands of virtual threads on several platform threads .

 

Create a virtual thread

The easiest way to create a virtual thread is to use Thread class . Use Loom, We got a new builder Methods and factory Method to create a virtual thread .

Runnable task = () -> System.out.println("Hello, world");

// Platform thread
(new Thread(task)).start();
Thread platformThread = new Thread(task);
platformThread.start();

// Virtual thread
Thread virtualThread = Thread.startVirtualThread(task);
Thread ofVirtualThread = Thread.ofVirtual().start(task);

// Virtual thread created with a factory
ThreadFactory factory = Thread.ofVirtual().factory();
Thread virtualThreadFromAFactory = factory.newThread(task);
virtualThreadFromAFactory.start();

This example first shows us how to create a platform thread , Then there is an example of a virtual thread . Both virtual threads and platform threads are represented by Runnable Is the parameter , And return an instance of the thread . Besides , Start a virtual thread and we are used to calling start() Method to start the platform thread is the same .

 

use Concurrency API Create a virtual thread

Loom Also for Concurrency API Added a new executor to create a new virtual thread . new VirtualThreadPerTaskExecutor Return an implementation ExecutorService Interface actuator , Just like other actuators . Let's take a look at using Executors.newVirtualThreadPerTaskExecutor() Method to get a using virtual threads ExecutorService Example .

Runnable task = () -> System.out.println("Hello, world");
ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
executorService.execute(task);

As you can see , It looks no different from existing actuators . In this case , We use Executors.newVirtualThreadPerTaskExecutor() To create a ExecutorService. This virtual thread executor executes each task on a new virtual thread . from VirtualThreadPerTaskExecutor There is no limit to the number of threads created .

 

I can use existing thread executors executors Do you ?

The short answer is OK , You can use existing executors and virtual threads by providing them with a virtual thread factory . please remember , These executors are created to assemble threads , Because the cost of creating platform threads is very high . It may be feasible to use an executor that aggregates threads in conjunction with virtual threads , But this kind of ignores the meaning of virtual threads . You don't need to assemble them , Because their creation cost is very low .

ThreadFactory factory = Thread.ofVirtual().factory();
Executors.newVirtualThreadPerTaskExecutor();
Executors.newThreadPerTaskExecutor(factory); // Same as newVirtualThreadPerTaskExecutor
Executors.newSingleThreadExecutor(factory);
Executors.newCachedThreadPool(factory);
Executors.newFixedThreadPool(1, factory);
Executors.newScheduledThreadPool(1, factory);
Executors.newSingleThreadScheduledExecutor(factory);

In the first line , We created a virtual thread factory , It will handle thread creation of the executor . Next , We call... For each actuator new Method , And provide it with the factory we just created . Be careful , Call with a virtual thread factory newThreadPerTaskExecutor With direct call newVirtualThreadPerTaskExecutor It's the same .

 

Completable future

When we use CompletableFuture when , We try to call get Before we put our actions in series chain turn , Because of the call get Blocking threads . With virtual threads , call get There will be no more thread blocking . No use get The punishment , You can use it anytime , Without writing asynchronous Code . This makes writing and reading Java Code becomes easier .

 

Structured concurrency

Because the thread creation cost is very low ,Project Loom Also for Java Brings structured concurrency . Through structured concurrency , You bind the life cycle of a thread to a code block . In your code block , You create the threads you need , And leave the code block when all threads complete or stop .

System.out.println("---------");
try (ExecutorService e = Executors.newVirtualThreadPerTaskExecutor()) {
    e.submit(() -> System.out.println("1"));
    e.submit(() -> System.out.println("2"));
}
System.out.println("---------");

Try-with-resources Statement can be used ExecutorService, because Project Loom use AutoCloseable Interface extended Executor. stay try in , We submit all the tasks that need to be completed , Once the thread is complete , We'll leave try. The output in the console will look like this .

---------
2
1
---------

The second dashed line will never be printed between numbers , Because the thread is waiting try-with-resources Completion .

 

summary

The project is still in the preview stage , Before we see it in production ,API May change . But explore new API, See what performance improvements it has brought us , It's pretty good .

 

原网站

版权声明
本文为[Solution jdon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202281153417528.html