Java deleteOnExit and addShutdownHook - what comes first?

I have several temporary files that I call deleteOnExit(). I also have an executable file that I register in addShutdownHook()to run on a call System.exit.

Is there any guarantee that temporary files will still be available when my shutdown hook is launched?

+5
source share
1 answer

When we look at the underlying implementations, both are dealing with Shutdown-Hook.

  1. When we are dealing with addShutdownHook (ApplicationShutdownHooks), we have a piece of code, as shown below in our code.

    Runtime.getRuntime().addShutdownHook(new Thread() {
          public void run() { 
                <<---Do the Implementations here--->>
          }
        });
    

Java ApplicationShutdownHooks , , Runtime, http://www.docjar.com/html/api/java/lang/Runtime.java.html.

class ApplicationShutdownHooks {
    /* The set of registered hooks */
    private static IdentityHashMap<Thread, Thread> hooks;
    static {
        try {
            Shutdown.add(1 /* shutdown hook invocation order */,
                false /* not registered if shutdown in progress */,
                new Runnable() {
                    public void run() {
                        runHooks();
                    }
                }
            );
  1. , File.deleteOnExit(), Java , .

            // DeleteOnExitHook must be the last shutdown hook to be invoked.
            // Application shutdown hooks may add the first file to the
            // delete on exit list and cause the DeleteOnExitHook to be
            // registered during shutdown in progress. So set the
            // registerShutdownInProgress parameter to true.
            sun.misc.SharedSecrets.getJavaLangAccess()
                .registerShutdownHook(2 /* Shutdown hook invocation order */,
                    true /* register even if shutdown in progress */,
                    new Runnable() {
                        public void run() {
                           runHooks();
                        }
                    }
            );
    

    . , , JavaSourceCode, : http://hg.openjdk.java.net/icedtea/jdk7/jdk/file/10672183380a/src/share/classes/java/io/DeleteOnExitHook.java http://hg.openjdk.java.net/icedtea/jdk7/jdk/file/10672183380a/src/share/classes/java/io/File.java

Shutdown Hook , . , Shutdown Hooks . , :

ApplicationShutdownHooks: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook (java.lang.Thread)

deleteOnExit: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#deleteOnExit()

, ApplicationShutdownHooks, deleteOnExit(), deleteOnExit() , JVM.

. , deleteOnExit() , , , , :

Path path = FileSystems.getDefault.getPath(".");
File asFile = path.toFile();
asFile.deleteOnExit();
-1

All Articles