Asynchronous Execution WrapperFeb 10th, 2008 | By raja shankar kolluru | Category: design, java, optimization
- On IoC containers & Stateful components
- Java & Performance
- App Optimization – Asynchronous Pre-fetching Strategies
- Application Optimization – Design in Retrospect
- Perf Analysis – Browser Caches & Response Code 304
- Perf Analysis – Web Layer & Browser
- Performance Analysis of a web application
- Asynchronous Execution Wrapper
- KPI – Key Performance Indicators
With the advent of Java 5 , asynchronous execution has become an easy thing to code. One has to be just grab hold of an ExecutorService from the java.util.concurrent library and start passing it a runnable. The only problem with this is that our class has to implement the Runnable interface which is not often desirable.
My intention was to open the doors of this to every interface – not just Runnable. I wanted to create a class that is capable of implementing any interface. So let us say I have a Foo interface. There are a few criteria around Foo.
- A method of Foo either returns a void.
- returns a meaningful value but in the process does something to expedite future calls (such as caching the result of the current call)
Let us say I have a FooImpl which implements Foo but does so synchronously.
I want to automatically make FooImpl asynchronous. I want to write a class that wraps FooImpl. This class should implement Foo during runtime. This way, the consumer of Foo does not know that it is dealing with any asynchronous stuff. It merely calls Foo methods and voila! they get executed asynchronously and none the wiser for it. I wanted to use JDK proxies to create a runtime implementation of Foo. So combining these two thoughts, I created a simple class AsyncExecutor.
This class implements the InvocationHandler to take advantage of the java reflection interface proxy. Separate asynchronous proxies are created for every tuple of Interface, Implementation to wrap and executor service. Notice how the static method’s signature uses java generics to convey its meaning precisely.
This class can be very useful for imbibing asynchronous behavior to synchronous classes.
Raja has been blogging in this forum since 2006. He loves a technical discussion any day. He finds life incomplete without a handy whiteboard and a marker.