tags:

views:

19

answers:

1

Hi,

I have this problem. In order to create a response for a single http request, I have to do several tasks that can be performed concurrently. I can perform those tasks in a Executor (thread pool) but then I have to worry about concurrency (synchronization) in my web app. Is there a better way to solve this problem without using thread pool?

Thanks,

+1  A: 

Using an Executor takes care of the messy details of thread synchronization, so it should be the easiest way to perform multiple tasks concurrently. You just submit jobs to the executor and wait for them to finish.

If these background tasks access some shared resource (especially in-memory data structures), then this access needs to be coordinated. The easiest way is to avoid shared resources, but if you can do that depends on what you actually need to do. If you must have shared resources, you can use Java synchronization primitives, or some other utilities from the concurrency package.

You cannot have multiple threads and not think about synchronization. No silver bullet here.

(By the way, even without multiple threads for a single web request, you probably have to consider threading issues in a web application anyway, because the same web server can be hit by multiple requests simultaneously).

Thilo
I was thinking about 2 possible solutions: 1 is having 2 web container that is identical and one web container is forwarding to another one. So the real task is perform in another container. The second solution is putting all the tasks into a jms queue and waiting for results coming back. However both of those solution requires 2 web containers. What do you think about that?
Sean Nguyen
What kind of tasks are we talking about? If they can be finished in a few seconds, a thread pool in the same web container with the request waiting for the result seems appropriate. If they take a long time (more than ten seconds), you should probably use something like JMS and not make the request wait (return immediately, show a progress bar, poll for completion with new requests).
Thilo
it expects to be finished in a few second. Is it a good practice to have thread pool inside your web container?
Sean Nguyen
I don't see a problem with that, and I would assume it is more common than using JMS. Just make sure that you shut it down properly, when the container wants to shut down the web app (ServletContextListener would be a good place).
Thilo