当前位置:网站首页>Asynchronous callback future mode of concurrent mode
Asynchronous callback future mode of concurrent mode
2022-07-29 03:18:00 【Program cat Dagang】
Future Pattern ( Get results asynchronously , Self realization )
The traditional serial process is as follows :
Waiting will be blocked when getting data , Get the data and then perform other tasks .
and Future The mode will immediately return a voucher (Future), At this time, you can perform other tasks ; Wait for the data to pass through the previous Future Just get the data from the voucher , The flow is as follows: :
Let's implement a simple Future Pattern :
First, analyze and design the following objects :
- Main The system starts , call Client Request , Get immediate return FutureData
- Client client , Send to get Data Request , Return immediately FutureData, And start thread assembly RealData
- Data Interface to return data
- FutureData Virtual data , It's a voucher , Assembly required RealData
- RealData Real data , Slow build
The code is as follows :
Data Interface :
public interface Data {
String getResult() throws InterruptedException;
}
RealData class :
public class RealData implements Data{
private String content;
public RealData(String content){
this.content = content;
}
@Override
public String getResult() {
return content;
}
}
FutureData class :
public class FutureData implements Data {
// Are you ready to
private boolean isReady;
// Assemble real data
private RealData realData;
@Override
public synchronized String getResult() {
// Not ready , Then block and wait
while (!isReady){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return realData.getResult();
}
public synchronized void setRealData(RealData realData){
if(isReady){
return;
}
this.realData = realData;
this.isReady = true;
// Notify other threads
notifyAll();
}
}
Client class :
public class Client {
// Request data
public FutureData request(String queryStr){
FutureData futureData = new FutureData();
// Start the thread to assemble real data asynchronously
new Thread(()->{
// The long-running
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Build real data
RealData realData = new RealData("hello future," + queryStr);
futureData.setRealData(realData);
}).start();
// Return immediately
return futureData;
}
}
Main Procedure class :
public class Main {
public static void main(String[] args) {
Client client = new Client();
FutureData futureData = client.request(" test ");
// Do other things
System.out.println(" Do something else 1");
System.out.println(" Do something else 2");
// To get the results
String result = futureData.getResult();
System.out.println(" The asynchronous result is :"+result);
}
}
Output results :
Do something else 1
Do something else 2
The asynchronous result is :hello future, test
JDK Medium Future Pattern
Here's the picture , yes JDK1.8 The encapsulation of Future Pattern realization .(1.5 It introduces Future Pattern ,1.8 Is more powerful , Provides CompletableFuture)
among :
class MyCallableRealizedCallableInterfacecall()Method will return real data ( Similar to self implementation Future Data interface in patternDataOfgetResult()Method )- FutureTask Be similar to FutureData, Are used as immediate return credentials in asynchronous calls
- Thread pools are similar to Client, Are used to perform tasks
The following is JDK Of future Example :
MyCallable class :
public class MyCallable implements Callable<String> {
private String str;
public MyCallable(String str){
this.str = str;
}
@Override
public String call() throws Exception {
// Simulate time-consuming operations
Thread.sleep(2000);
return "hello jdk future," + str;
}
}
Main Program :
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(1);
FutureTask<String> futureTask = new FutureTask<>(new MyCallable(" test "));
// Submit tasks
executor.submit(futureTask);
System.out.println(" Deal with other logic 1");
System.out.println(" Deal with other logic 2");
String result = futureTask.get();
System.out.println("(jdk) The result of asynchronous processing is :"+result);
executor.shutdown();
}
}
Data results :
Deal with other logic 1
Deal with other logic 2
(jdk) The result of asynchronous processing is :hello jdk future, test
in addition ,JDK Of Future Mode Future The interface also provides some advanced functions .
boolean cancel(boolean mayInterruptIfRunning);// Cancel the task
boolean isCanclled();// Whether it has been cancelled
boolean isDone();// Has it been completed
V get(long timeout,TimeUnit unit);// Get results within the timeout
Guava Expand Future Pattern
JDK Of Future In the pattern ,future.get() It's blocked , It is not conducive to high concurrency development .Guava Enhanced Future Pattern , Added callback interface at completion , send future When it is finished, the application can be automatically notified for acquisition processing .
Change the above program to guava How to set the callback function , The code is as follows :
Main Program :
public class Main {
public static void main(String[] args){
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(4));
// Submit tasks
ListenableFuture<String> future = executorService.submit(new MyCallable(" test "));
// Add callback function
future.addListener(()->{
String result = null;
try {
result = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("(guava) The result of asynchronous processing is :"+result);
},MoreExecutors.directExecutor());
System.out.println(" Deal with other logic 1");
System.out.println(" Deal with other logic 2");
executorService.shutdown();
}
}
Output results :
Deal with other logic 1
Deal with other logic 2
(guava) The result of asynchronous processing is :hello guava future, test
Netty Expand Future Pattern
netty Support settings are also provided in Future Extension of callback .
public class Main {
public static void main(String[] args) {
// establish netty Thread group
EventExecutorGroup group = new DefaultEventExecutorGroup(4);
// Submit tasks
Future<String> future = group.submit(new MyCallable(" test "));
System.out.println(" Deal with other logic 1");
System.out.println(" Deal with other logic 2");
future.addListener(new FutureListener<String>(){
@Override
public void operationComplete(Future<String> future) throws Exception {
String result = future.get();
System.out.println("(netty) The result of asynchronous processing is :"+result);
}
});
group.shutdownGracefully();
}
}
JDK8 Of CompletableFuture
JDK8 Provided in CompletableFuture More powerful .CompletableFuture Realized CompletionStage Interface and Future Interface , The former is an extension of the latter , Added asynchronous callback 、 Streaming 、 Multiple Future The ability to combine processing , send Java It is more smooth and convenient when dealing with multi task collaborative work .
Use CompletableFuture The transformation supports asynchronous callback methods , The code is as follows :
MySupplier class :
public class MySupplier implements Supplier<String> {
private String str;
public MySupplier(String str){
this.str = str;
}
@Override
public String get() {
// Simulate time-consuming operations
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello jdk CompletableFuture," + str;
}
}
Main Program :
public class Main {
public static void main(String[] args){
CompletableFuture<String> future = CompletableFuture.supplyAsync(new MySupplier(" test "),
Executors.newFixedThreadPool(1));
future.whenCompleteAsync((r,t)->{
System.out.println("(CompletableFuture) The result of asynchronous processing is :"+r);
});
System.out.println(" Deal with other logic 1");
System.out.println(" Deal with other logic 2");
}
}
Output results :
Deal with other logic 1
Deal with other logic 2
(CompletableFuture) The result of asynchronous processing is :hello jdk CompletableFuture, test
summary
- stay
JDK1.5Provided inFuturePattern , Blocked when getting data , So other frameworks (guavaandnetty) YesFutureThe pattern is extended , Callback functions are supported . - stay
JDK1.8Provided inCompletableFuture, Supports more powerful asynchronous callbacks 、 Streaming 、 MultipleFutureThe ability to combine processing .
Reference material
- Books Ge Yiming * 《Java High concurrency programming 》
边栏推荐
- Regular expression bypasses WAF
- "PHP Basics" output approximate value of PI
- C和指针 第3章 语义“陷阱” 3.5 空指针并非字符串
- MySQL operation database data error: fatal error encoded during command execution
- Design of smoke temperature, humidity and formaldehyde monitoring based on single chip microcomputer
- Reproduce 20 character short domain name bypass and XSS related knowledge points
- A case of gradually analyzing the splitting of classes -- colorful ball collisions
- Wechat's crazy use of glide - life cycle learning
- Several methods of converting object to string
- C陷阱与缺陷 第3章 语义“陷阱” 3.6 边界计算与不对称边界
猜你喜欢

【打开新世界大门】看测试老鸟如何把API 测试玩弄在鼓掌之间

Detailed steps for installing MySQL 8.0 under Linux

13_ue4进阶_蒙太奇动画实现一边走一边攻击

Unity 之游戏特效

Does domestic ERP have a chance to beat sap?

Example analysis of while, repeat and loop loops in MySQL process control

STC MCU drive 1.8 'TFT SPI screen demonstration example (including data package)

力扣刷题之分数加减运算(每日一题7/27)
![[freeswitch development practice] media bug obtains call voice flow](/img/14/9a359403606c312b30733d4a015fa5.png)
[freeswitch development practice] media bug obtains call voice flow

Verilog:阻塞赋值和非阻塞赋值
随机推荐
Why did I choose the test when the development salary was high?
MYSQL入门与进阶(十一)
Feedback function of conference OA
MYSQL入门与进阶(十四)
Chapter 2 VRP command line
【C】数组
July 28, 2022 Gu Yujia's study notes
Regular expression bypasses WAF
Apache文件管理自学笔记——映射文件夹和基于单ip多域名配置apache虚拟机
【科技1】
GJB common confused concepts
MySql的安装配置超详细教程与简单的建库建表方法
Three military product baselines (functional baseline, distribution baseline, product baseline) and the documents contained in the baseline
军品研制过程-转阶段
C traps and defects Chapter 3 semantic "traps" 3.7 evaluation order
美联储再加息,75基点 鲍威尔“放鸽”,美股狂欢
shell脚本总结
接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
Object转String的几种方法
Shardingsphere's level table practice (III)