当前位置:网站首页>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 .
边栏推荐
- 【概率论与数理统计】期末复习抱佛脚:公式总结与简单例题(完结)
- How to develop programming learning with zero foundation during college
- Ansible PlayBook et ansible roles (3)
- SQL tuning guide notes 11:histograms
- SQL调优指南笔记13:Gathering Optimizer Statistics
- 六月集训(第10天) —— 位运算
- [QNX hypervisor 2.2 user manual] 4.2 supported build environments
- Jin AI her power | impact tech, she can
- talent showing itself! Oceanbase was selected into the 2021 "sci tech innovation China" open source innovation list
- June training (day 10) - bit operation
猜你喜欢

Things about the kotlin collaboration process - pipeline channel

How to specify your webpage's language so Google Chrome doesn't offer to translate it

SQL调优指南笔记8:Optimizer Access Paths

Kotlin collaboration process - flow

Ansible summary (VI)

Palindrome linked list and linked list intersection problem (intersecting with Xinyi people) do you really know?

NiO User Guide

JVisualVM初步使用

Modstartcms modular station building system v3.3.0 component function upgrade, event triggering enhancement

Preliminary use of jvisualvm
随机推荐
Yyds dry goods inventory solution Huawei machine test: weighing weight
Palindrome linked list and linked list intersection problem (intersecting with Xinyi people) do you really know?
SQL tuning guide notes 16:managing historical optimizer statistics
SQL调优指南笔记12:Configuring Options for Optimizer Statistics Gathering
The 2023 campus recruitment officially opened! Oceanbase would like to make an interview with you this spring
Ansible基础和常用模块(一)
What is the difference between volatile variables and atomic variables?
Have you really learned the common ancestor problem recently?
SQL tuning guide notes 12:configuring options for optimizer statistics gathering
[QNX hypervisor 2.2 user manual] 4.3 obtain the host component
How to develop programming learning with zero foundation during college
2023届校园招聘正式开启!OceanBase 想和你在这个春天约一场面试
[QNX hypervisor 2.2 user manual] 4.2 supported build environments
【QNX Hypervisor 2.2 用户手册】4.3 获取host组件
June training (day 12) - linked list
February 27th
Ansible foundation and common modules (I)
Build a highly available database
Dolphin-2.0.3 cluster deployment document
SQL tuning guide notes 13:gathering optimizer statistics