I have another project for the Open Source Central: AsyncWorker. I am tired of writing similar asynchronous call infrastructure from scratch in every project. This is why I am going to write the AsyncWorker. At the highest level, there will be an interface (class?) AsyncWorker defined as
interface AsyncWorker {
<T> T invoke(T t);
<T> T invoke(T t, int maxWait);
<T> InvocationIdentity execute(T t, AsyncCallback callback);
}
The implementation of the AsyncWorker will be flexible enough to use simple heap, JMS or database queues to store the invocations and the API is very easy to start using in your existing projects. For example, if you wanted to turn a synchronous call into asynchronous one with as little coding as possible, you’d write
@Controller
class ExistingController {
private SomeService someService;
private AsyncWorker asyncWorker;
@RequestMapping(...)
public void index() {
// this.someService.doWork(1, 2, "hello"); #A
this.asyncWorker.invoke(this.someService). #B
doWork(1, 2, "hello");
}
}
That should be it! Instead of synchronous call on line #A, you will use the AsyncWorker on line #B. The AsyncWorker will queue the invocation of the doWork method of SomeService and will return immediately. Because of the asynchronous nature of the call, the value returned from the method call will be default for the return type (0 for int, long, 0.0 for double, float, null for object reference, etc.).
The alternatives, as you can guess, are using the invoke(T, int) method, which will also invoke any method of T asynchronously, but will wait up to the specified timespan before returning. If the invoked method completes within the specified timespan, the returned value will be valid, otherwise it will be the default value.
Finally, you can use the execute method to schedule the asynchronous call — this gives you the highest degree of control and you will get an InvocationIdentity object back. You will be able to use the returned InvocationIdentity to monitor the progress of the call.
Call for comments
If you think this is a good idea, please comment and add any features you’d find useful. We will be releasing this project under the Open Source Central under Apache Licence.