Java的异步编程
1. 概述
随着对编写非阻塞代码的需求不断增长,我们需要异步执行代码的方法。
在本教程中,我们将介绍几种在 Java中实现异步编程 的方法。我们还将探讨一些提供开箱即用解决方案的 Java 库。
2. Java中的异步编程
2.1. Thread
我们可以创建一个新线程来异步执行任何操作。随着 Java 8 中lambda 表达式 的发布,它变得更加简洁易读。 让我们创建一个新线程来计算和打印一个数字的阶乘:
int number = 20;
Thread newThread = new Thread(() -> {
System.out.println("Factorial of " + number + " is: " + factorial(number));
});
newThread.start();
2.2. Future
从 Java 5 开始,Future接口提供了一种使用*FutureTask *执行异步操作的方法。
我们可以使用*ExecutorService 的submit方法异步执行任务并返回FutureTask*的实例。
所以让我们找到一个数字的阶乘:
ExecutorService threadpool = Executors.newCachedThreadPool();
Future<Long> futureTask = threadpool.submit(() -> factorial(number));
while (!futureTask.isDone()) {
System.out.println("FutureTask is not finished yet...");
}
long result = futureTask.get();
threadpool.shutdown();
这里我们使用了Future接口提供的isDone方法来检查任务是否完成。完成后,我们可以使用get方法检索结果。
2.3. CompletableFuture
**Java 8结合了Future和CompletionStage 引入了CompletableFuture 。**它提供了多种方法,如supplyAsync、runAsync和thenApplyAsync用于异步编程。
现在让我们使用CompletableFuture代替FutureTask来查找数字的阶乘:
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
while (!completableFuture.isDone()) {
System.out.println("CompletableFuture is not finished yet...");
}
long result = completableFuture.get();
我们不需要显式使用ExecutorService。CompletableFuture在内部使用ForkJoinPool 来异步处理任务。因此,它使我们的代码更加简洁。
3. Guava
Guava 提供了ListenableFuture 类来执行异步操作。
首先,我们将添加最新的guava Maven 依赖项:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
然后让我们使用ListenableFuture找到一个数字的阶乘:
ExecutorService threadpool = Executors.newCachedThreadPool();
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
ListenableFuture<Long> guavaFuture = (ListenableFuture<Long>) service.submit(()-> factorial(number));
long result = guavaFuture.get();
这里*MoreExecutors 类提供了 ListeningExecutorService 类的实例。然后ListeningExecutorService.submit 方法异步执行任务并返回ListenableFuture*的实例。
Guava 还有一个Futures 类,它提供了submitAsync、scheduleAsync和transformAsync等方法来链接ListenableFuture,类似于CompletableFuture。
例如,让我们看看如何使用Futures.submitAsync 代替ListeningExecutorService.submit 方法:
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
AsyncCallable<Long> asyncCallable = Callables.asAsyncCallable(new Callable<Long>() {
public Long call() {
return factorial(number);
}
}, service);
ListenableFuture<Long> guavaFuture = Futures.submitAsync(asyncCallable, service);
这里submitAsync方法需要AsyncCallable 的参数,该参数是使用Callables 类创建的。
此外,Futures类提供了addCallback方法来注册成功和失败回调:
Futures.addCallback(
factorialFuture,
new FutureCallback<Long>() {
public void onSuccess(Long factorial) {
System.out.println(factorial);
}
public void onFailure(Throwable thrown) {
thrown.getCause();
}
},
service);
4. EA异步
Electronic Arts 通过ea-async库 将 .NET 的 async-await 功能引入 Java 生态系统。
该库允许顺序编写异步(非阻塞)代码。因此,它使异步编程更容易并自然扩展。
首先,我们将最新的ea-async Maven 依赖添加到pom.xml:
<dependency>
<groupId>com.ea.async</groupId>
<artifactId>ea-async</artifactId>
<version>1.2.3</version>
</dependency>
然后我们将使用 EA 的*Async 类提供的await方法转换前面讨论的CompletableFuture*代码:
static {
Async.init();
}
public long factorialUsingEAAsync(int number) {
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
long result = Async.await(completableFuture);
}
在这里,我们调用静态块中的Async.init 方法来初始化Async运行时检测。
Async检测在运行时转换代码,并重写对await方法的调用,使其行为类似于使用CompletableFuture链。
因此, 调用await方法类似于调用Future.join。
我们可以使用*–javaagent* JVM 参数进行编译时检测。这是Async.init方法的替代方法:
java -javaagent:ea-async-1.2.3.jar -cp <claspath> <MainClass>
现在让我们看另一个顺序编写异步代码的例子。
首先,我们将使用CompletableFuture类的thenComposeAsync和thenAcceptAsync等组合方法异步执行一些链操作:
CompletableFuture<Void> completableFuture = hello()
.thenComposeAsync(hello -> mergeWorld(hello))
.thenAcceptAsync(helloWorld -> print(helloWorld))
.exceptionally(throwable -> {
System.out.println(throwable.getCause());
return null;
});
completableFuture.get();
然后我们可以使用 EA 的*Async.await()*转换代码:
try {
String hello = await(hello());
String helloWorld = await(mergeWorld(hello));
await(CompletableFuture.runAsync(() -> print(helloWorld)));
} catch (Exception e) {
e.printStackTrace();
}
该实现类似于顺序阻塞代码;但是,await方法不会阻塞代码。
正如所讨论的,对await方法的所有调用都将由Async工具重写,以类似于Future.join方法。
因此,一旦hello方法的异步执行完成, Future结果就会传递给mergeWorld方法。然后使用CompletableFuture.runAsync方法将结果传递给最后一次执行。
5. Cactoos
Cactoos 是一个基于面向对象原则的 Java 库。 它是 Google Guava 和 Apache Commons 的替代品,提供用于执行各种操作的通用对象。 首先,让我们添加最新的*cactoos * Maven 依赖项:
<dependency>
<groupId>org.cactoos</groupId>
<artifactId>cactoos</artifactId>
<version>0.43</version>
</dependency>
这个库为异步操作提供了一个*Async 类。 所以我们可以使用 Cactoos 的Async*类的实例找到一个数字的阶乘:
Async<Integer, Long> asyncFunction = new Async<Integer, Long>(input -> factorial(input));
Future<Long> asyncFuture = asyncFunction.apply(number);
long result = asyncFuture.get();
这里apply方法使用ExecutorService.submit方法执行操作,并返回Future接口的实例**。
同样,Async类具有提供相同功能但没有返回值的exec方法。
注意:Cactoos 库处于开发的初始阶段,可能还不适合生产使用。
6. Jcabi-Aspects
Jcabi-Aspects通过AspectJ AOP 方面为异步编程提供了@Async 注解。
首先,让我们添加最新的jcabi-aspects Maven 依赖项:
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-aspects</artifactId>
<version>0.22.6</version>
</dependency>
jcabi-aspects库需要 AspectJ 运行时支持,因此我们将添加aspectjrt Maven 依赖项:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
接下来,我们将添加jcabi-maven-plugin 插件,该插件将二进制文件与 AspectJ 方面结合起来。该插件提供了为我们完成所有工作的ajc目标:
<plugin>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-maven-plugin</artifactId>
<version>0.14.1</version>
<executions>
<execution>
<goals>
<goal>ajc</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
</dependencies>
</plugin>
现在我们都准备好使用 AOP 方面进行异步编程了:
@Async
@Loggable
public Future<Long> factorialUsingAspect(int number) {
Future<Long> factorialFuture = CompletableFuture.completedFuture(factorial(number));
return factorialFuture;
}
当我们编译代码时,该库将通过 AspectJ 编织注入 AOP 建议来代替*@Async注解, 以异步执行factorialUsingAspect*方法。
让我们使用 Maven 命令编译该类:
mvn install
jcabi-maven-plugin的输出可能如下所示:
--- jcabi-maven-plugin:0.14.1:ajc (default) @ java-async ---
[INFO] jcabi-aspects 0.18/55a5c13 started new daemon thread jcabi-loggable for watching of @Loggable annotated methods
[INFO] Unwoven classes will be copied to /tutorials/java-async/target/unwoven
[INFO] jcabi-aspects 0.18/55a5c13 started new daemon thread jcabi-cacheable for automated cleaning of expired @Cacheable values
[INFO] ajc result: 10 file(s) processed, 0 pointcut(s) woven, 0 error(s), 0 warning(s)
我们可以通过检查Maven 插件生成的jcabi-ajc.log文件中的日志来验证我们的类是否正确编织:
Join point 'method-execution(java.util.concurrent.Future
com.blogdemo.async.JavaAsync.factorialUsingJcabiAspect(int))'
in Type 'com.blogdemo.async.JavaAsync' (JavaAsync.java:158)
advised by around advice from 'com.jcabi.aspects.aj.MethodAsyncRunner'
(jcabi-aspects-0.22.6.jar!MethodAsyncRunner.class(from MethodAsyncRunner.java))
然后我们将该类作为一个简单的 Java 应用程序运行,输出将如下所示:
17:46:58.245 [main] INFO com.jcabi.aspects.aj.NamedThreads -
jcabi-aspects 0.22.6/3f0a1f7 started new daemon thread jcabi-loggable for watching of @Loggable annotated methods
17:46:58.355 [main] INFO com.jcabi.aspects.aj.NamedThreads -
jcabi-aspects 0.22.6/3f0a1f7 started new daemon thread jcabi-async for Asynchronous method execution
17:46:58.358 [jcabi-async] INFO com.blogdemo.async.JavaAsync -
#factorialUsingJcabiAspect(20): '[[email protected]](/cdn_cgi/l/email_protection)[Completed normally]' in 44.64µs
正如我们所见,异步执行任务的库创建了一个新的守护线程jcabi-async。
同样,日志记录由库提供的@Loggable 注解启用。