Idan Fridman

About Idan Fridman

Idan is Software engineer with experience in Server side technologies. Idan is responsible for various infrastructure models in the software industry(Telecommunications, Finance).

Invoking Async method call using Future object in Spring

The next example will demonstrate an async method call inside the Spring container. Why do we need async method calls? In some cases we don’t really know if replay is expected or when a result supposed to be delivered back. Traditional way In the Java EE world of handling async calls is using Queue/Topic. We could do the same in Spring but if needed a simple async invocation, you could do it easily by following the next steps:

1. Declare Asynchronous Gateway:

 
 

<bean id="executionLogicImpl"
 class="com.test.components.execution_gateway.ExecutionLogicImpl"
 abstract="false" lazy-init="default" autowire="default">
 </bean>

2. declare interface method with return type – Future(Java 5+):

More information on Future object: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html

public interface ExecutionLogic
{

 public Future<String> doSomeExecutionLogic(String message);

}

* As soon as the GatewayProxyFactoryBean notice a return type Future it will switch the method into an async mode by having AsyncTaskExecutor

3. We will create a job channel which will collect all requests and send them asynchronously to another class(ExecutionLogicImpl) in order to process them(some random business logic):

<int:channel id="job1Channel" />

<int:service-activator input-channel="job1Channel" ref="executionLogicImpl" method="doSomeExecutionLogic" />

The class ExecutionLogicImpl:

public class ExecutionLogicImpl
{
 public String doSomeExecutionLogic(String msg)
 {
 try
 {
 System.out.println("doing long work on message="+msg);
 Thread.sleep(8000);

}
 catch (InterruptedException e)
 {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 return msg + "_completed";

}

}

Test class:

import com.test.components.execution_gateway.ExecutionLogic;

public class testExeceution

{

...
ExecutionLogic executionLogic;
public String sendMsgToExecutionQueue(String msg)
 {
 Future<String> processedMessage = executionLogic.doSomeExecutionLogic(msg);

String finalResult = "";
 try
 {
 finalResult = " " + processedMessage.get(TIMEOUT, TimeUnit.SECONDS);
 return "1 final result: " + finalResult; // + " " + response;
 }
 catch (ExecutionException e)
 {
 return "1 final result: " + e + finalResult;// + " " + response;
 }
 catch (TimeoutException tex)
 {
 return "1 final result: " + tex + finalResult; // + " " + response;
 }
 catch (Exception ex)
 {
 return "1 final result: " + ex + finalResult;// + " " + response;
 }

}
...
}

* You can enable timeout using the Future object for cases a response will never be returned.

So what’s happening here? We sending input to be executed asynchronously. The sender is waiting for response (asynchronously) as soon as the request finish it’s processing a result will be sent back to the sender.
 

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Invoking Async method call using Future object in Spring"

  1. venkat says:

    my requirement through webservice polling approach, I have to send 10 reqeusts asynchronously and get responses.
    please can me help me

Leave a Reply


one − 1 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books