java - 如何用 Java 返回我自己的 future ?

标签 java concurrency future

在 Java 8 中,我正在编写一个 DAO 方法,它调用一个返回 ListenableFuture 的方法(在本例中,它是一个返回 ResultSetFuture 的 Cassandra 异步查询)。

但是,我仍然坚持应该如何将 Future 返回给 DAO 方法的调用者。我不能只返回 ResultSetFuture,因为 future 会返回一个 ResultSet。我想处理 ResultSet 并返回一个不同的对象。例如:

public ListenableFuture<ThingObj> queryForThingAsync(String thingId) {
    ListenableFuture<ResultSet> rsFuture = db.getSession().executeAsync(QueryBuilder.select().all().from("thingSchema","Thing").where(eq("thingId",thingId)));
    // Now what? How do I create a ListenableFuture<ThingObj> given a ListenableFuture<ResultSet> and a method that can convert a ResultSet into a ThingObj?
}

最佳答案

既然您使用的是 Guava 的 ListenableFuture,最简单的解决方案是 transform来自 Futures 的方法:

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future.

有几种使用方法,但由于您使用的是 Java 8,最简单的方法可能是方法引用:

public ListenableFuture<ThingObj> queryForThingAsync(String thingId) {
    ListenableFuture<ResultSet> rsFuture = db.getSession().executeAsync(QueryBuilder.select().all().from("thingSchema","Thing").where(eq("thingId",thingId)));
    return Futures.transform(rsFuture, Utils::convertToThingObj);
}

关于java - 如何用 Java 返回我自己的 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33487969/

相关文章:

scala - 在Scala 2.10中杀死或使Future超时

java - 如何用future来中断一个线程,想要通过future发出的中断来执行一些任务

java - JAVA中的异常处理、创建日志并继续程序

java - 损坏的表单数据 : premature ending on Alcatel OT900A

java - 验证帐户并获取权限

java - 处理线程最大执行时间的最佳方法(在 Java 中)

c++ - 如何锁定多个锁,其中一些是共享的,一些不是 C++

r - 我们如何配置shinyserver开源支持并发用户

scala - Akka 在响应非 Actor 代码时避免包装 future

java - 二维 JButton 数组中的简单 ActionListener