Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SpringFrameWork @Async for methods that return void

I'm using the Spring Boot framework as my backend.

This is one of the calls I want to do asynchronously - it just saves a user into my mongoDB database:

@Async
public Future<Void> saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    return new AsyncResult<Void>(mongoTemplate.save(user));
}

The method gives me an errors as mongoTemplate.save(user) returns a void value and not a Void object.

I tried to change the method by substituting in void as follows but it does not work as Future<void> and AsyncResult<void> is not accepted:

@Async
public Future<void> saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    return new AsyncResult<void>(mongoTemplate.save(user));
}

Is there anyway to run a method that returns void in an asynchronous way on Spring?

like image 689
Simon Avatar asked Nov 27 '15 17:11

Simon


1 Answers

Try the following:

@Async
public void saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    mongoTemplate.save(user);
}

Future needs to be used only when there is return type other than void.

like image 79
prem kumar Avatar answered Nov 16 '22 02:11

prem kumar