当前位置:网站首页>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 .
边栏推荐
- [sword finger offer] sword finger offer 35 Replication of complex linked list
- Ansible roles project case (IV)
- 在同花顺开户证券安全吗,证券开户怎么开户流程
- SQL tuning guide notes 17:importing and exporting optimizer statistics
- June training (day 10) - bit operation
- [sword finger offer simple] sword finger offer 24 Reverse linked list
- Exception encountered by selenium operation element
- [data analysis] data clustering and grouping based on kmeans, including Matlab source code
- [Jianzhi offer] Jianzhi offer 09 Implementing queues with two stacks
- What are thread scheduler and timeslicing?
猜你喜欢

About the solution to "the application cannot start normally 0xc00000022" after qt5.15.2 is installed and qtcreator is started

leetcodeSQL:574. Elected

How to prevent phishing emails? S/mime certificate to help!

2021 rust survey results released: 9354 questionnaires collected

NiO User Guide

NoSQL - redis configuration and optimization (II) high availability, persistence and performance management

Ansible-大总结(六)

Kdd2022 | graphmae: self supervised mask map self encoder

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

A puzzle about + =
随机推荐
Ansible foundation and common modules (I)
Interpretation of OCP function of oceanbase Community Edition
SQL调优指南笔记9:Joins
2021 rust survey results released: 9354 questionnaires collected
Ansible PlayBook et ansible roles (3)
Npoi create word
Pat grade A - 1167 Cartesian tree (30 points) (buildtree + level traversal)
Ansible playbook and variable (II)
MySQL介绍和安装(一)
Mr. Sun's version of JDBC (21:34:25, June 12, 2022)
Unity 常用3D数学计算
SQL调优指南笔记11:Histograms
Recommended Chinese font in the code input box of Oracle SQL developer
SQL调优指南笔记6:Explaining and Displaying Execution Plans
Oracle SQL Developer的代码输入框中推荐使用的中文字体
PE installation win10 system
February 27th
NiO User Guide
Implementation of master-slave replication and master-master replication for MySQL and MariaDB databases
How to implement a simple publish subscribe mode