Search code examples
javamultithreadingweb-servicesasynchronousjava-threads

How to execute background computations in an asynchronous thread(In a REST Web service)


I have a REST web service which caters HTTP requests. After the data is fetched from the database, I would like to run a background thread and start analyzing the data, which takes some extra amount of time to complete. And this data has nothing to do with the response, we are just logging the computed analysis.

I tried following method based on my own understanding of Threads concept. But in both cases HTTP response is returned just after the background computation is done, so basically the computation thread and the original thread are not asynchronous and the computation thread is stopping the response thread till the analysis is done.

  1. Started a daemon thread. I expected the daemon thread to run in the background meanwhile the HTTP method sends the response. But, not true. Response is displayed only after the computation is done in this thread. Aren't daemon threads supposed to run in the background even when the parent thread exits? (Please read the comments of james, to know how starting a daemon could've been a problem here)

    Callable<Boolean> computeCallable = new CallableComputeProcess();
    Thread t=new Thread(computeCallable);
    t.setDaemon(true);
    t.start();

P.S: Computation thread is a child thread I created inside a parent thread.

Is there a way to start a thread asynchronously, that lets the background computations just run in the background without stopping the http response?


Solution

  • Answering my own question:

    I used FutureTask concept and ExecutorService, on which I never call get() method. As we know that the focus doesn't shift to the thread(with the FutureTask) until we call FutureTask.get() method. Since I never called get() method, the computation thread runs in the background meanwhile returning the HTTP response. And it continues to run in the background till the computation is over.

    ExecutorService executor = Executors.newFixedThreadPool(1);
    
    Callable<Boolean> computeCallable = new CallableComputeProcess();
    
    executor.submit(scimCallable);
    

    And the CallableComputeProcess goes like this:

    public class CallableComputeProcess implements Callable<Boolean> {
    public Boolean call() {
            //do computation
            return true;
        }
    }
    

    This doesn't stop/hinder the main thread which carries out the response and runs in the background.