Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing a timeout value when using @Async for a method using Spring 3.0

I looked through the documentation but couldn't find if there is a way to specify a timeout for async operations spawned when using @Async annotated methods using Spring 3.0.

Is there a way to do that? I think this is pretty essential whenever making triggering an async computation.

like image 650
Aayush Puri Avatar asked Sep 24 '10 07:09

Aayush Puri


People also ask

What will happen if you specify @async over a public method of a spring bean?

Simply put, annotating a method of a bean with @Async will make it execute in a separate thread. In other words, the caller will not wait for the completion of the called method.

What does @async do in spring?

The @EnableAsync annotation switches on Spring's ability to run @Async methods in a background thread pool. This class also customizes the Executor by defining a new bean. Here, the method is named taskExecutor , since this is the specific method name for which Spring searches.

Does @async work on private method?

Never use @Async on top of a private method. In runtime, it will not able to create a proxy and, therefore, not work.


1 Answers

Timeouts are not provided by the @Async annotation, since the timeout should be decided by the caller of the function, not the function itself.

I'm assuming you're referring to the timeout on an @Async-annotated method which returns a result. Such methods should return an instance of Future, and the get() method on Future is used to specify the timeout.

e.g.

@Async
public Future<String> doSomething() {
   return new AsyncResult<String>("test");
}

and then

Future<String> futureResult = obj.doSomething();  // spring makes this an async call
String result = futureResult.get(1, TimeUnit.SECOND);
like image 166
skaffman Avatar answered Sep 23 '22 19:09

skaffman