Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Async not working for method having return type void

I wanted to make a method writing to DB as async using @Async annotation.

I marked the class with the annotation @EnableAsync:

@EnableAsync
public class FacialRecognitionAsyncImpl {

    @Async
    public void populateDataInPushQueue(int mediaId, int studentId) {
        //myCode
    }
}

while calling the populateDataInPushQueue method, the write operation should be executed in another thread and the flow should continue from the class I am calling this method. But this is not happening and the program execution is waiting for this method to complete.

like image 326
Dhruv Singh Chandel Avatar asked May 30 '19 17:05

Dhruv Singh Chandel


People also ask

Can we return void in async method?

In short, if your async method is an event handler or a callback, it's ok to return void .

How do you enable the use of @async Annotation in query method?

To enable the asynchronous processing, add the @EnableAsync annotation to the configuration class. The @EnableAsync annotation switches on Spring's ability to run @Async methods in a background thread pool.

Can we use @async 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.

Can a task return void?

Task return typeSuch methods return void if they run synchronously. If you use a Task return type for an async method, a calling method can use an await operator to suspend the caller's completion until the called async method has finished.


1 Answers

The @Async annotation has few limitations - check whether those are respected:

  • it must be applied to public methods only
  • it cannot be called from the same class as defined
  • the return type must be either void or Future

The following can be found at the documentation of @EnableAsync:

Please note that proxy mode allows for the interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.

Another fact is that the class annotated with @EnableAsync must be a @Configuration as well. Therefore start with an empty class:

@EnableAsync
@Configuration
public class AsyncConfiguration { }
like image 115
Nikolas Charalambidis Avatar answered Nov 13 '22 07:11

Nikolas Charalambidis