Reputation: 324
is it possible to have a method be called when the main thread or the entire program terminates? I'm aware of Thread's .join() method, but I do not think it will work on the main thread. For example, if I create a temporary directory, I would like to delete that temporary directory when the program terminates, but I would like for that to happen when the program terminates, not after something like the main method.
I do not want this:
public static void main() {
....Do something
....Delete temp directory
}
Upvotes: 2
Views: 1122
Reputation: 2778
Simply add a shutdown hook..
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("ERMEHGERDDD");
}
});
From the Javadoc: A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.
The shutdown hook will be called when all non-deamon threads finish or if System.exit() is called.
Upvotes: 3
Reputation: 5851
As user:Mad Programmer mentioned above, you could use ShutdownHook.
public static void main(String[] args)
{
ShutdownHookThread shutdownHook = new ShutdownHookThread();
Runtime.getRuntime().addShutdownHook(shutdownHook );
}
private static class JVMShutdownHook extends Thread
{
public void run()
{
// tempDirectory.delete();
}
}
Upvotes: 1
Reputation: 863
I see four possible methods.
Upvotes: 0