0

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 Answer 1

1

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).

4
  • 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? Oct 4, 2010 at 12:52
  • 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
    Oct 5, 2010 at 0:12
  • it expects to be finished in a few second. Is it a good practice to have thread pool inside your web container? Oct 5, 2010 at 3:31
  • 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
    Oct 5, 2010 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.