JVM shutting down

In this chapter you will learn:

  1. Exit and halt Java virtual machine
  2. How to add a shut down hook

Exit and halt Java virtual machine

  • void exit(int status)
    Terminates the currently running Java virtual machine by initiating its shutdown sequence.
  • void halt(int status)
    Terminates the currently running Java virtual machine.
public class Main {
  public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();
/*  j a va2 s  .c o  m*/
    runtime.exit(2);
  }
}

Shut down hook

We can add to do list for JVM shutting down. For example we can close resource or write to log file when the JVM is shutting down.

  • void addShutdownHook(Thread hook) Registers a new virtual-machine shutdown hook.
  • boolean removeShutdownHook(Thread hook) De-registers a previously-registered virtual-machine shutdown hook.
public class Main {
  public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();
//from j a  v a2s.c  o  m
    runtime.addShutdownHook(new Thread(){
      public void run(){
        System.out.println("Shut down");
        
      }
      
    });
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to get the number of processors available to the Java virtual machine
Home » Java Tutorial » Utility Classes
Java standard stream
Java system property get and set
Current time in millis second and nano second
Random UUID
JVM memory
JVM garbage collector
JVM shutting down
Processor count
OS system commands
Random class
Random value
Random value range
Compile Java source code
Timer and TimerTask