Showing posts with label Multi threading. Show all posts
Showing posts with label Multi threading. Show all posts

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
                MoreExecutors.listeningDecorator(ExecutorService);
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 {  
      @SuppressWarnings("unchecked")  
      public static void main(String a[]) {  
           ListeningExecutorService pool = MoreExecutors  
                     .listeningDecorator(Executors.newCachedThreadPool());  
           final ListenableFuture<String> future = pool.submit(new Callable() {  
                @Override  
                public String call() throws Exception {  
                     try {  
                          int a = 10 / 0;  
                     } catch (Exception e) {  
                          throw e;  
                     }  
                     return "done";  
                }  
           });  
           Futures.addCallback(future, new FutureCallback() {  
                @Override  
                public void onSuccess(Object object) {  
                     System.out.println("Success.");  
                }  
                public void onFailure(Throwable throwable) {  
                     System.out.println("Failure.");  
                }  
           });  
      }  
 }  


 Output  
 Failure.

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

Thursday, 27 August 2015

Daemon Thread


What is Daemon Threads ?

Daemon threads are those threads which perform some helper functions or provide services to non-daemon threads(user threads).When JVM starts up,it creates garbage collector thread or some housekeeping threads except main thread .this threads are called Daemon threads. 

Daemon threads runs in background to provide services to user threads.Daemon threads are low priority threads.When no user thread is running JVM terminates all the daemon threads .

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class TestDaemonThreads extends Thread {  
      public static void main(String[] args) {  
           TestDaemonThreads daemonThread = new TestDaemonThreads();  
           TestDaemonThreads normalThread = new TestDaemonThreads();  
           daemonThread.setDaemon(true);  
           daemonThread.start();  
           normalThread.start();  
      }  
      public void run() {  
           if (Thread.currentThread().isDaemon()) {  
                System.out.println("Daemon Thread");  
           } else {  
                System.out.println("Normal Thread");  
           }  
      }  
 }  



 Output:-  
 Daemon Thread  
 Normal Thread  

Use of Daemon Threads:-

Daemon threads performs housekeeping tasks such as removing unwanted entries from memory cache,releasing memory of unused objects etc.

Enjoy Learning.


Shutdown Hooks


It is one of the concurrency concept.JVM(Java Virtual Machine) can shutdown in an orderly or abruptly manner. An orderly shutdown is nothing but when all normal threads terminates successfully,or by calling System.exit(),or by closing it from special keys like Ctrl+C.
JVM can also be shutdown abrubtly by killing the JVM process or by some OS related issues.

What is Shutdown Hooks ?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().
JVM does not give any guarantee on the order in which shutdown hooks are started.In orderly shutdown JVM starts all registered shutdown hooks.

When all shutdown hooks have completed their task,JVM may choose to run finalizers if runFinalizersOnExit is true.JVM does not stop any of the application thread that are still running at shutdown time.they automatically terminated when JVM halts.Also JVM allows to run application threads concurrently with shutdown hooks.In an abrupt shutdown,shutdown hooks will not run.


Example of Shutdown Hook:-

/**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class TestShutdownHook {  
      // shutdown hook thread can be used to perform cleaning of resources.  
      private static class ShutDownHook extends Thread {  
           public void run() {  
                System.out.println("shutdown hook thread started");  
           }  
      }  
      public static void main(String[] args) {  
           ShutDownHook jvmShutdownHook = new ShutDownHook();  
           Runtime.getRuntime().addShutdownHook(jvmShutdownHook);  
           System.out.println("Register Shutdown Hook");  
           System.out.println("calling System.exit() to close the program");  
           System.exit(0);  
           System.out.println("Program Finished");  
      }  
 }  

Output:-  
 Register Shutdown Hook  
 calling System.exit() to close the program  
 shutdown hook thread started  

Advantage of Shutdown Hooks:-

It can be used for service or application cleanup,such as deleting unwanted file, releasing resources like db related resources,file operation resources etc.

 Note:-Shutdown hooks must be thread safe and they should use synchronization when   
 accessing shared data.They should not assume the state of the application(such as all worker   
 thread have completed) at any point of time.They should complete their task as quickly as   
 possible because their existence delays the JVM termination at a time when user may be   
 expecting the JVM to shutdown quickly.