Tuesday, 1 September 2015

ListenerExecutorService and its Example

What is ListenerExecutorService ?
ListenerExecutorService is almost same as ExecutorService except  in ListenerExecutorService ,callback methods can be registered and that will be called once execution of task reach some defined state.ListenerExecutorService returns ListenableFuture instances.ListenableFuture instance allows to register callback methods which will get executed once the task gets completed.

In order to create ListenerExecutorService ,you need to use decorator which accepts ExecutorService as parameter
You can use any of the ExecutorService (newFixedThreadPool(),newSingleThreadExecutor(),etc)

Sample Example:-

 import java.util.concurrent.Callable;  
 import java.util.concurrent.Executors;  
 import com.google.common.util.concurrent.FutureCallback;  
 import com.google.common.util.concurrent.Futures;  
 import com.google.common.util.concurrent.ListenableFuture;  
 import com.google.common.util.concurrent.ListeningExecutorService;  
 import com.google.common.util.concurrent.MoreExecutors;  
  * @author Dixit  
 public class ListeningExecutorServiceExample {  
      public static void main(String a[]) {  
           ListeningExecutorService pool = MoreExecutors  
           final ListenableFuture<String> future = pool.submit(new Callable() {  
                public String call() throws Exception {  
                     try {  
                          int a = 10 / 0;  
                     } catch (Exception e) {  
                          throw e;  
                     return "done";  
           Futures.addCallback(future, new FutureCallback() {  
                public void onSuccess(Object object) {  
                public void onFailure(Throwable throwable) {  


So in this program ,the callback methods onSuccess and onFailure will be called once execution of the task is finished.In this case an arithmetic exception occurs which calls the callback method onFailure.You don't need to explicitly check the state of your ListenableFuture object ,as the registered callbacks will handle the states ,once the task is completed.

you need to download the guava jar ,here is the link http://www.java2s.com/Code/Jar/g/Downloadguavajar.htm

Enjoy programming

No comments:

Post a Comment