nevin
nevin

Reputation: 73

Running a time taking process in a separate thread spawning from a servlet filter

There is a servlet filter in my application from which I need to invoke a web service which takes some time to return response and then store the response in session to be used later. I want that by the time this time-taking process takes place my filter should proceed and should continue invoking the other filters too so that the performance is not affected.

So this is what I am thinking of doing inside doFilter(). Create a different thread for this purpose.

log.debug("start filter");
CustomThread ct=new CustomThread();
ct.start(); //invoke web service in run()
log.debug("continuing with filter");

Considering the fact that more that 1000 users will be hitting the application, will this approach work properly. Will this condition fail for some scenario? Please suggest if I need to take a different route.

Upvotes: 0

Views: 294

Answers (2)

JB Nizet
JB Nizet

Reputation: 691943

The main problem is that you start a new thread each time. This is time consuming, and it can bring the server to its knees if you get many concurrent requests, because you don't have any limit on the number of spawned threads.

I would use a ThreadPoolExecutor instead, which would solve those two problems.

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359966

You should use an Executor of some sort rather than worrying about thread management yourself. The Executors class provides a variety of simple ways to create executor instances.

Upvotes: 1

Related Questions