TODAY JAVA SCHOOL

In java school, programming, design, computer general knowledge, web application, software, web services, social media, digital marketing, oops, concept of programming language, oops feature, console media, graphics medium, first programming, c, c ++ , Java, PHP, SQL, MySQL, HTML, HTML_5, J_query, JavaScript, Bootstrap, Framework, images with logos, examples, shared and explained.

https://www.amazon.in/b?node=26373545031&linkCode=ll2&tag=1234567801cdb-21&linkId=3b9882431b00409b44141e0344b35a15&language=en_IN&ref_=as_li_ss_tl

Breaking

Thursday 16 April 2020

Java Shutdown Hook | Java Shutdown Hook Example

                  Java Shutdown Hook

The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

example java shutdown hook

Fig: java shutdown hook


When does the JVM shut down?

The JVM shuts down when:
o    user presses ctrl+c on the command prompt
o    System.exit(int) method is invoked
o    user logoff
o    user shutdown etc.
The addShutdownHook(Thread hook) method
The addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine.


 Syntax:

public void addShutdownHook(Thread hook){}  
The object of Runtime class can be obtained by calling the static factory method getRuntime(). For example: Runtime r = Runtime.getRuntime();


Factory method

The method that returns the instance of a class is known as factory method.

Simple example of Shutdown Hook

class MyThread extends Thread{  

    public void run(){  
        System.out.println("shut down hook task completed..");  
    }  
   }  
      
  public class TestShutdown1{  
  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) {}  
    }  
   }  

Output:


     Now main sleeping... press ctrl+c to exit
       shut down hook task completed..

No comments:

Post a Comment