Search code examples
javamultithreadingshutdown-hook

what is tha actuall use of shut down hook in java


I m learning java, i m unable to understand the actual use of shutdown hook in java means where it actually use ?

class MyThread extends Thread{  
    public void run(){  
        System.out.println("shut down hook task completed..");  
    }  
}  

public class Shutdown {  
public static void main(String[] args)throws Exception {  

Runtime r=Runtime.getRuntime();  
r.addShutdownHook(new MyThread());  

System.out.println("Now main sleeping... press ctrl+c to exit");  
try{Thread.sleep(3000);}catch (Exception e) {}  
}  
}  

i got this when i search for it could anyone help me to understand it


Solution

  • Whenever you have some resource that must be closed (or released) on shutdown. Typical examples include connections to external databases (perhaps within a connection pool), or displaying a message to the user (as in your post), or a file handle, or any and all of the above.