首页 > 解决方案 > 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;

    }
}

进程应在生成响应后立即返回,而写入数据库操作应在后台完成。守护线程可以在后台执行此任务,但不保证任务完成。因此,如果您知道任何其他方法,请告诉我。谢谢。

标签: javamultithreadingbackground-process

解决方案


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
        }
    }
}

推荐阅读