1 回答
TA贡献1851条经验 获得超5个赞
从执行器服务使用 Future.get(超时)应该可以相当干净地处理这个问题。
例如:
ExecutorService executor = Executors.newCachedThreadPool();
// ... set up builder as before ...
Future<Response> responseFuture = executor.submit(
() -> builder.post(Entity.json(new Gson().toJson(request))));
try {
Response response = responseFuture.get(timeout, TimeUnit.SECONDS);
// return normal response here
} catch (TimeoutException ex) {
executor.submit( () -> {
Response lateResponse = responseFuture.get();
// send overThreshold alert email here
// Dummy return - prefer Callable to Runnable here for exception handling
return null;
} );
// return a message to user here saying their payment could not be processed
}
可以选择适合,也可以同样是应用程序中其他位置的共享线程池。ExecutorService
添加回答
举报