I have a public interface, Synchronous, that gets exposed to several service layer classes. Its intent is to lookup an object graph based on the id being passed, do some business logic and then pass it on to the Spring Asynchronous method Asynchronous.doWork to finish the rest of the task.
I'm trying to use the Spring AsyncResult but I'm unsure what the returned object WorkResult actually gets returned to. Do I need to put a handler somewhere in the SynchronousImpl? Ideas?
Sync Public Service:
public class SynchronousImpl implements Synchronous {
private Asynchronous async;
//business logic
public void doWork(long id){
async.doWork(id);
}
}
Async Worker Class:
public class Asynchronous {
@Async
public Future<WorkResult> doWork(long id){
//business logic
WorkResult result = new WorkResult(id, "Finished");
return new AsyncResult<WorkResult>(result);
}
}
A Future
has nothing to do with Spring, Future
are classes that belong to the Java 6 concurrency framework.
A typical use case is this:
public void doWork(long id) {
Future<WorkResult> futureResult = async.doWork(id);
//Do other things.
WorkResult result = futureResult.get(); //The invocation will block until the result is calculated.
}
After the async method is started (that is where Spring helps with its @Async
annotation) the caller gets immediately the Future
Object. But the future object is not the result, it is just a wrapper/placeholder/proxy/reference for the real result.
Now the caller and the worker run in parallel and can do different things. When the caller invokes futureResult.get();
and the real result is not calculated yet, this thread gets blocked until the result is provided by the worker. (When the caller invokes futureResult.get();
and the real result is already calculated, he gets the result immediately)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With