Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring AsyncResult and Future Return

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);
    }
}
like image 507
c12 Avatar asked Jan 23 '14 16:01

c12


1 Answers

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)

like image 144
Ralph Avatar answered Oct 02 '22 18:10

Ralph