mashedpotats
mashedpotats

Reputation: 324

Run a method on main thread/program termination?

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

Answers (3)

slipperyseal
slipperyseal

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

a3.14_Infinity
a3.14_Infinity

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

Noxious Reptile
Noxious Reptile

Reputation: 863

I see four possible methods.

  1. Use your own Thread subclass with an overridden run() method. Add a finally block for thread termination. 2.Use a Runnable with similar decoration, perhaps as a wrapper around the supplied Runnable. A variant of this is to subclass Thread in order to apply this wrapper at construction time. 3.Create a 2nd thread to join() on the real thread and thus detect its termination. 4.Use instrumentation to rewrite the Thread.run() method as above.

Upvotes: 0

Related Questions