Wednesday, 28 December 2011

JavaEE Revisits Design Patterns: Asynchronous

Although you may not find Asynchronous method calls listed as a design pattern, I find it worth to mention. So here comes the last post of my JavaEE Revisits Design Patterns series.

Asynchronous method calls is not much more than multithreading. Basically it refers to a a method call which would run in a separate thread, thus the main (caller) thread does not need to wait for the result of the execution of the called method. In the age of web programming, developers mostly delegate the threading issues to the running server and creating new threads can be tricky and sometime dangerous on web servers since they usually like to manage the threads themselves.

However, playing nice with the servers while using threads can be very simple with JavaEE. Annotating a method with @Asynchronous would be enough to tell the JavaEE container to run the called method in a separate thread asynchronously.
To test asynchronous execution lets add a new method marked with the Asynchronous annotation to our previous example.

Although the log might differ, you should still clearly see the startService method is called which fired the event followed by the execution of the second logging method. The startService method waited until the execution of the second log method is complete. However, the first logging method started and end its execution independently from either of the other methods execution.

Although this example is based on void methods, its quite simple to use Future<> as a return type and to receive a result asynchronously.

Asynchronous annotation is very easy to use and can be very useful in situations where you do not want to wait for the execution of the called method.