Asynchronous Call in Java
Tuesday, July 30, 2013
The
java.util.concurrent.ExecutorService
interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService
is thus very similar to a thread pool. In fact, the implementation of ExecutorService
present in the java.util.concurrent
package is a thread pool implementation:
/**
* Asynchronous call to invoke any method
* * *
* @author Manesh Abhimanyu
* @param String Input 1
* @param String Input 2
*/
public void asyncServiceMethod( final String input1, final String input2)
{
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Runnable task = new Runnable(){
public void run()
{
try {
invokeMyMethod( input1, input2 );
} catch ( Exception ex ) {
// handle error which cannot be thrown back
}
}
};
executor.execute( task );
} catch ( Exception e ) {
// handle error which cannot be thrown back
} finally {
// gargabe collect
executor.shutdown();
}
}
* Asynchronous call to invoke any method
* * *
* @author Manesh Abhimanyu
* @param String Input 1
* @param String Input 2
*/
public void asyncServiceMethod( final String input1, final String input2)
{
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Runnable task = new Runnable(){
public void run()
{
try {
invokeMyMethod( input1, input2 );
} catch ( Exception ex ) {
// handle error which cannot be thrown back
}
}
};
executor.execute( task );
} catch ( Exception e ) {
// handle error which cannot be thrown back
} finally {
// gargabe collect
executor.shutdown();
}
}
More reading:
Labels: Asynchronous, Asynchronous call, concurrency, example, ExecutorService, ExecutorService example, java
posted by MIGHTYMAK @ 11:52 PM, ,