Mar*_*ark 5 java multithreading jersey thread-safety
我正在与付款处理器集成,并试图处理以下情况:
因此,我需要从用户界面的HTTP调用中开始对付款处理器的API调用,然后,如果花费超过60秒,请结束HTTP调用并将错误返回给用户,然后,如果API调用了付款处理器最终成功(例如70秒后),向管理团队发送电子邮件。
我在想这样的事情:
import javax.ws.rs.client.*;
import java.util.Timer;
import java.util.TimerTask;
...
boolean overThreshold = false;
int timeout = 60; // seconds
TimerTask task = new TimerTask() {
@Override
public void run() {
overThreshold = true;
// return a message to user here saying their payment could not be processed
}
};
new Timer(true).schedule(task, timeout * 1000);
Client client = ClientBuilder.newClient();
WebTarget webTarget
= client.target({url of payment processor});
Invocation.Builder builder = webTarget.request()
.header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
final Response response = builder.post(Entity.json(new Gson().toJson(request)));
if (overThreshold) {
// send alert email here
}
Run Code Online (Sandbox Code Playgroud)
存在一些问题,例如,该run()方法的返回值无效,overThreshold从内部类访问时出错。有没有更优雅的方式做到这一点?
从ExecutorService使用Future.get(timeout)应该可以很干净地处理它。
例如:
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
}
Run Code Online (Sandbox Code Playgroud)
的选择ExecutorService可以被调谐,以适应,或者同样可以是一个共享线程池在申请的其他地方。