Reputation: 1919
I would like to ask what is the best approach to run a long process from a java servlet. I have a webapp and when the client do a request it runs a servlet. This servlet should get some parameters from the request and then runs a process. This process may take a long time so I need to run it separately. When this process executed finish, it send an email with the results.
Thanks in advance.
Upvotes: 7
Views: 4292
Reputation: 5657
I see two possibilities to do this:
WebSphere MQ
Second approach have the advantage: if app not able to process the request now by some reason, the app can return to it later
Upvotes: 2
Reputation: 32983
Normally that kind of activities is delegated to another type of application module like a message driven bean and that seems to be the cleanest, and standards compliant solution to me. Although most servers won't complain if you create your own threads (which is forbidden by the standard but rarely enforced) the amount of management needed to set up your own job queue and pooled execution environment isn't really worth it in my opinion.
Upvotes: 2
Reputation: 24134
Though this sounds a bit dangerous that invocation of a servlet spawns a process (without proper throttling capabilities in place), you can spawn a process using Runtime.getRuntime().exec()
. Much better would be to use ProcessBuilder
to prepare the process arguments and spawn it.
Upvotes: 2
Reputation: 692221
Use a thread pool. Each time you receive a request, create a task and submit it to the thread pool. This will ensure too many requests don't bring the server to its knees, because you'e in control of how many concurrent threads you can have, and how many tasks can wait in the thread pool's queue of waiting tasks.
See the javadoc for Executors and ThreadPoolExecutor.
Upvotes: 5