views:

133

answers:

5

In Spring, is there a way to execute a task after returning a view or I need to create a ThreadPool and do it ?

Ex:

public ModelAndView handleRequest(HttpServletRequest request,
     HttpServletResponse response) throws Exception {

  Map<Object, Object> data = new HashMap<Object, Object>();

            //do some stuff
            executeSomeStuffButDontWaitForTheResult();    
  return new ModelAndView("result", data);
 }
+2  A: 

Spring contains an Aspect Oriented Programming framework which allows you to specify code to be run before and after various parts of your code that may be the kind of thing you are looking for. Take a look at the Spring documentation: Aspect Oriented Programming with Spring.

Tendayi Mawushe
A: 

If you really don't want to wait for the result, you should run it in a different thread anyways. For example, using Spring's Task Executor.

axtavt
A: 

You can use a Task Executor like @axtavt said or you could use Asynchronous JMS

non sequitor
A: 

Yup, this is just a matter of either spawning a thread or (better) grabbing a thread from a pool. It has nothing to do with Spring.

But in looking at your code, you're leaving open the possibility that the view is just going to render a partially populated or even empty map. (And if you don't pass the map to the executeSomeStuffButDontWaitForTheResult() method, it is guaranteed that the map will be empty.) It's not clear what you're attempting to do, but I doubt you intend to return a partial or empty map, and the map isn't going to fill up while the user is looking at the web page. If you describe more carefully what you're trying to do we might have some alternative ideas for you.

Willie Wheeler
I didn't fill the view because it's an exemple. I just wanted to render the view but continue to do some work after that doesn't need to be rendered. (To return the result faster to the client)
Mike
+1  A: 

If you're using Spring 3, the easiest way to do this would be to annotate your executeSomeStuffButDontWaitForTheResult method with @Async.

In your configuration:

<task:annotation-driven executor="yourTaskExecutor" scheduler="yourTaskScheduler"/>

For more info here

Michal Bachman