abhi
abhi

Reputation: 177

@Async in spring mvc working without a Future return type?

Sometimes when I am using @Async without return type of Future it returns null but sometimes it returns String. In documentation it is mentioned that return type of Future is must. I am confused why this is happening?

e.g.this one is working

@Service
public class MyClass implements MyClass2{

  @Async
  @Override
  public String getString() {

    return "hello";
  }
}

Upvotes: 1

Views: 2383

Answers (1)

Fritz Duchardt
Fritz Duchardt

Reputation: 11900

Please don't return a String from an @Async method. This is against the intentions of the makers. Excerpt from the Spring Execution & Scheduling docu:

Even methods that return a value can be invoked asynchronously. However, such methods are required to have a Future typed return value. This still provides the benefit of asynchronous execution so that the caller can perform other tasks prior to calling get() on that Future.

If your asynchronous method has a return type, it MUST be a Future object!

Why? Because otherwise the method invoker won't be able to wait for the completion of the Thread that has handled the @Async method. The waiting for Thread-completion is handled by Future.get

Upvotes: 3

Related Questions