Given a FooService with read and write operations backed by a repository, I want to provide an asynchronous variant of it to be used in a Spring REST web service (potentially using Akka as it’s already a candidate for other problems…).
So far I have the verbose and somewhat clunky variant
class AsyncFooService extends FooService {
private final ExecutorService executor = Executors.newCachedThreadPool();
private final FooService delegate = ...
@Override
public void writeSomeThing(Obj o) {
executor.submit(new Runnable() {
@Override
public void run() {
delegate.writeSomeThing(o);
}
});
}
// repeat same override & executor semantics for all write* routines
}
What other good variants are there in achieveing asynchronous operations to the service?
To limit the scope, let’s not directly consider Proxies as they don’t provide a solution in themselves.
First off I think there is a typo in your code – you’re calling the same writeSomeThing() method from within the run() creating infinite loop?
Aside from this, I think this is pretty much how would you do it in plain Java – using Executors. More verbose for sure, but you could move this code to the proxy/interceptor to your sync implementation, which would submit task to executor and return control to the caller, therefore leaving sync implementation free of this non functional logic. Then you could either call sync implementation directly to get sync behavior or call proxy to get async, or perhaps proxy cold handle both depending on the parameters etc.
If you want less coding to do and having enough flexibility there are certainly options available – beside Akka, which you already mentioned, you could look at Apache Camel’s SEDA queues or to any lightweight messaging solution which would let you to post tasks to the work queues for processing outside of your main thread.