首页 > Java > java教程 > 正文

Unlock Faster Async Programming with Java Futures

DDD
发布: 2024-09-20 08:19:39
原创
467 人浏览过

Unlock Faster Async Programming with Java Futures

In our previous article, we explored the world of ListenableFuture. Now, let's dive deeper into more advanced techniques, specifically focusing on transformations and chaining. Imagine we have a ListenableFuture obtained from an asynchronous service. Additionally, we have a simple method:

Document parse(String xml) {//...
登录后复制

Instead of working with the String itself, we need the Document. One approach would be to resolve the Future and process the String. However, a more elegant solution is to apply a transformation once the results are available, making our method behave as if it always returned ListenableFuture. This is remarkably straightforward:

final ListenableFuture future = //...
 
final ListenableFuture documentFuture = Futures.transform(future, new Function() {
    @override    public Document apply(String contents) {
        return parse(contents);
    }
});
登录后复制

Or, for better readability:

final Function parseFun = new Function() {
    @override    public Document apply(String contents) {
        return parse(contents);
    }
};
 
final ListenableFuture future = //...
 
final ListenableFuture documentFuture = Futures.transform(future, parseFun);
登录后复制

While Java syntax may have its limitations, let's focus on what we've achieved. Futures.transform() doesn't wait for the underlying ListenableFuture to apply the parse() transformation. Instead, it registers a callback, ready to be notified whenever the given future completes. This transformation is applied dynamically and transparently for us at the right moment. We still have a Future, but this time wrapping a Document.

Now, let's take it a step further. We also have an asynchronous, possibly long-running method that calculates the relevance (whatever that means in this context) of a given Document:

ListenableFuture calculateRelevance(Document pageContents) {//...
登录后复制

Can we somehow chain it with the ListenableFuture we already possess? First attempt:

final Function> relevanceFun = new Function>() {
    @override    public ListenableFuture apply(Document input) {
        return calculateRelevance(input);
    }
};
 
final ListenableFuture future = //...
final ListenableFuture documentFuture = Futures.transform(future, parseFun);
final ListenableFuture> relevanceFuture = Futures.transform(documentFuture, relevanceFun);
登录后复制

For more information on enhanced asynchronous programming possibilities, visit this link.

以上是Unlock Faster Async Programming with Java Futures的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板