0

I'm attempting to build a Java Servlet task that has a runtime of about ~15-20 minutes that takes arguments from a HTML form. I have a couple of questions regarding this:

  1. Will the task continue to run even after the user closes the browser? I Googled this and it seems the process will continue to execute even after browser close. I just want to confirm this.

  2. While searching for the answer for the above question, I came across a post (or a couple of them) that stated that for such 'intensive' (I would consider mine intensive as it takes around 15-20 minutes to complete) tasks, it's better to have a separate program run the task than containing it in the servlet program. So, do I just execute another Java program from the servlet class?

And now for my final question, will multiple user requests be processed independent of each other? As in, will the servlet have a separate thread or instance for each request? If so, will my execution of another Java program from the servlet class lead to any problems?

vigneshwerv
  • 155
  • 11

1 Answers1

2

There are a few items to discuss, each with their own (part of a) solution:

  • Do you really want the task to continue if the browser closes? Spawn a new thread for the task (Trying to write to the browser outputstream when browser is already closed will make the thread die in an exception) See Executor
  • Do you want concurrent requests to be handled in parallel? How many in parallel? See ThreadPoolExecutor
  • Do you want feedback to the browser (user) during the long running task? See Async servlets

The servlet container will make sure that parallel requests are handled concurrently, each in their own thread. But they will share the instance of the Servlet class. Therefore, you have to make your code thread safe.

About running a 'separate java program' or keeping the task in the servlet: it is best practice to separate different tasks in a program in different sections. Creating a new class for your long running task is better than keeping it in the servlet class. See Separation of concerns.

Community
  • 1
  • 1
Geert
  • 3,527
  • 1
  • 20
  • 16
  • The results aren't going to be displayed on the browser. They'll be mailed to the user, so that's of no issue here. My main concerns are if the servlet will run the task for each user request _independent of each other_ automatically or should I do that **and** should I dedicate a separate Java program for the task or can it be contained in the servlet class itself? – vigneshwerv Sep 09 '13 at 07:39
  • @vigneshwerv I added thread safety and separation of concerns to the answer – Geert Sep 09 '13 at 08:30