Reputation: 1
I have a Java servlet that launches a lengthy task that can be performed in the background after the response has been sent. I can tell from log entries that, even though launching the thread is the last thing I do in the servlet, the framework is still executing request related code after the new thread starts.
I am considering passing the current thread to the new thread's constructor (parentThread), saving that reference, and calling parentThread.join() as the first statement in run(). But that seems pretty kludgy.
Is there a better/more elegant solution?
Upvotes: 0
Views: 42
Reputation: 22
Have a look at the ThreadPoolExecutor class to see if this can better suit your needs rather than rolling your own threads. I would normally start the threads when the servlet initialises, and then the doGet() and doPost() methods just submit to the queue and return. The executor will run in the background whilst your servlet is running.
It would be useful to have more detail on the statement: "the framework is still executing request related code after the new thread starts."
Upvotes: 0
Reputation: 12029
Usually threads are pooled/recycled by the Servlet container, so there is little sense in waiting for the termination. If you can do the work independently of the current request, there should be no problem in spawning the thread anyway.
Depending on your ecosystem you should have a look at Spring executor services or even the @Asynchronous abstraction for scheduling background tasks. You might want to look at the asynchronous servlet API as well.
Upvotes: 1