View RSS Feed

My Java Tips

Asynchronous method calls

Rating: 1 votes, 5.00 average.
by , 11-07-2011 at 07:52 PM (5047 Views)
Methods called on the asynchronous proxy will be executed asynchronously, and the results can be obtained later on.

To execute methods asynchronously in EJB 3.0, one can use asynchronous proxy. This allows calling methods at an instance, and collecting the results later. Good thing is that there exist a JBoss extension to EJB 3.0, which allows obtaining asynchronous proxy from the remote or local interface of a stateful session bean, stateless session bean or service bean.

The following code snippet obtains the remote interface of the bean and then calls a method. Standard synchronous usage pattern is being used.

Java Code:
   InitialContext ctx = new InitialContext();
   Echo echo = (Echo)ctx.lookup(org.jboss.tutorial.asynch.bean.Echo.class.getName());
   System.out.println("-------- Synchronous call");
   String ret = echo.echo("normal call");
Now lest see how to obtain the asynchronous proxy and how to make a call via that. Doing this will invoke the method asynchronously :

Java Code:
   Echo asynchEcho = Asynch.getAsynchronousProxy(echo);
   System.out.println("-------- Asynchronous call");
   ret = asynchEcho.echo("asynchronous call");
   System.out.println("Direct return of async invocation is: " + ret);
Its easy as shown in the example above. You can obtain the asynchronous proxy by calling org.jboss.ejb3.asynchronous.Asynch.getAsynchronous Proxy() . All methods invoked on this proxy are invoked asynchronously, and the returned value will always be null.

I will prenset another example of asynchronous method calls in EJBeans.

Lets take another example for better understanding. In the given example, we call on the normal remote interface while "waiting" for the asynchronous call.

Java Code:
   System.out.println("-------- Synchronous call");
   ret = echo.echo("normal call 2");
After doing everything we wish to do while waiting for the asynchronus call to complete, we have to cast the asynchronus proxy to AsynchProvider and then have to get hold of the Future contained.

Java Code:
      System.out.println("-------- Result of Asynchronous call");
      AsynchProvider provider = (AsynchProvider)asynchEcho;
      Future future = provider.getFuture();
Now is the time to make sure that the asynchronus invocation has completed and then we should get the return value of the asynchronus invocation.

Java Code:
      System.out.println("Waiting for asynbch invocation to complete");
      while (!future.isDone())
      ret = (String)future.get();
Happy coding!!!

Submit "Asynchronous method calls" to Facebook Submit "Asynchronous method calls" to Digg Submit "Asynchronous method calls" to Submit "Asynchronous method calls" to StumbleUpon Submit "Asynchronous method calls" to Google

Tags: None Add / Edit Tags