java - java - 如何在进程返回java时运行保证完成的后台任务?
问题描述
我想做一些类似的事情-
class doSomeTask{
public static object do_method(object request){
//Perform some operation on request
response = doSomeOperation(request);
//Want to do this task in background
writeToDB(request, response);
return response;
}
}
进程应在生成响应后立即返回,而写入数据库操作应在后台完成。守护线程可以在后台执行此任务,但不保证任务完成。因此,如果您知道任何其他方法,请告诉我。谢谢。
解决方案
public class Test {
private static FutureTask<Void> future;
public static Object do_method(Object request) {
// Perform some operation on request
Object response = doSomeOperation(request);
// Want to do this task in background
future = new FutureTask<>(new Callable<Void>() {
@Override
public Void call() throws Exception
{
writeToDB(request, response);
return null;
}
});
// Start background thread and execute Callable (FutureTask is also a runnable)
new Thread(future).start();
return response;
}
public static Object doSomeOperation(Object request) {
return new Object();
}
public static void writeToDB(Object request, Object response) throws Exception {
throw new Exception(); // Simulation failure on SQL insert
}
public static void main(String[] args) {
Object request = new Object();
Object response = do_method(request);
// ... do some crazy stuff with response
try {
future.get(); // Wait for succesfull execution of background thread
} catch (Exception e) {
// Catch ExecutionException if any uncaught Exception in the background thread is thrown
}
}
}
推荐阅读
- join - KDB 如何连接具有不同列名的表
- android - E/FirebaseInstanceId:令牌检索失败:SERVICE_NOT_AVAILABLE
- checkbox - 在递归剔除中获取检查的属性
- c++ - 如何使头文件可以通过库名称包含?
- linux-kernel - Linux 是否在 mmap() 之后立即为进程分配内存?
- java - 对象是否应该与主 Activity 交互?
- python - 从 JSON 文件中提取名称
- python-3.x - 使用 Python 3.6 覆盖 Image Exif 中的 GPS 坐标
- scala - Swagger 工件在外部库中,但 IntellIJ 看不到
- teradata - TPT 脚本在运行时加载另一个文件