We've moved! — MindVault360 is now HexLab. Better design, more content & premium notes.

Visit HexLab →

MindVault360 has moved!

We've upgraded to HexLab — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at hexlab

Monday, September 9, 2024

Java Shutdown Hook

 (Tap the post to see more)


In Java, a shutdown hook is a thread that is registered with the Java Virtual Machine (JVM) to perform cleanup tasks or release resources when the JVM is shutting down. Shutdown hooks are useful for ensuring that certain operations are executed before the program terminates, regardless of whether it exits normally or due to an unexpected error.


Example 01:


package com.java.Multi_threading;


public class ShutdownHookExample {

public static void main(String[] args) {

// Registering a shutdown hook using Runtime

Runtime.getRuntime().addShutdownHook(new Thread(() -> {

// Code to be executed during shutdown

System.out.println("Shutdown hook executed");

}));


// Rest of your program

System.out.println("Program is running");


// Simulate a program that does some work

for (int i = 0; i < 5; i++) {

System.out.println("Working... " + i);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}


// Exiting the program

System.exit(0);

}

}

← Back Next →

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home