Java process when exited anonymously with Kill or pkill unix comamnds does not delete temp files

When a Java tool is run, it creates temporary files in a folder. If terminated correctly, these files are removed, but if terminated with kill or pkill, these files are not removed. Is there a way to send a signal to the java process to remove these files before the process finishes? Please help me to solve this problem. Thanks in Advance

-1


source to share


2 answers


You can add a stop hook and clear whatever you need explicitly.

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { 
        //put your shutdown code here 
    }
});

      



This is the same as java.io.File#deleteOnExit

for you.

0


source


Seems to File.deleteOnExit()

be fragile when it comes to completing the process. In contrast, using the NIO API with StandardOpenOption.DELETE_ON_CLOSE

seems more reliable, even if its spec only says, "If the method is close

not called, then an effort is made to delete the file when the Java virtual machine ends."

eg. when running the following program:



File f1=File.createTempFile("deleteOnExit", ".tmp");
f1.deleteOnExit();
final Path f2 = Files.createTempFile("deleteOnClose", ".tmp");
FileChannel ch = FileChannel.open(f2, StandardOpenOption.DELETE_ON_CLOSE);
System.out.println(f1);
System.out.println(f2);
LockSupport.parkNanos(Long.MAX_VALUE);
// the following statement is never reached, but it’s here to avoid
// early cleanup of the channel by garbage collector
ch.close();

      

and killing the process while it hangs on parkNanos

, the JVM leaves the deleteOnExit

tmp file when the file is properly deleted deleteOnClose

on my machine.

0


source







All Articles