【发布时间】:2017-02-24 09:12:02
【问题描述】:
我必须在 Spark API 实现中调用长时间运行的方法。这些方法返回 CompletableFutures,所以我想通过触发 Spark 在回调中回答客户端请求来释放当前线程。 据我所知,这对于 Spark 来说是不可能的,但我想确保我没有忽略任何东西。 为了说明这个问题,请参见下面的小代码示例。
import spark.Spark;
import java.util.concurrent.CompletableFuture;
public class HelloSpark {
public static void main(String[] args) {
Spark.get("/what_i_have_to_do", (req, res) -> {
CompletableFuture<String> f = callToSlowWorker();
return f.get();
});
Spark.get("/what_i_would_like_to_do", (req, res) -> {
CompletableFuture<String> f = callToSlowWorker();
f.whenComplete((answer, throwable) -> {
if(throwable != null){
// send error to requesting client
res.status(500);
res.body(throwable.getMessage());
} else {
// send answer to requesting client
res.body(answer);
}
// trigger spark to return the response to the client
// ...?!?
});
return null; // obviously not what I want, just to make this sample code compile
});
}
static CompletableFuture<String> callToSlowWorker(){
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
return "Hello World";
});
}
}
【问题讨论】:
标签: java multithreading callback future spark-java