Deleting a temporary folder/file via shutdown-hook

Deleting a temporary folder/file is a task that can be accomplished by the operating system or specialized tools. However, sometimes, we need to control this programmatically and delete a folder/file based on different design considerations.

A solution to this problem relies on the shutdown-hook mechanism, which can be implemented via the Runtime.getRuntime().addShutdownHook() method. This mechanism is useful whenever we need to complete certain tasks (for example, cleanup tasks) right before the JVM shuts down. It is implemented as a Java thread whose run() method is invoked when the shutdown-hook is executed by JVM at shut down. This is shown in the following code:

Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customDirPrefix = "logs_";
String customFilePrefix = "log_";
String customFileSuffix = ".txt";

try {
Path tmpDir = Files.createTempDirectory(
customBaseDir, customDirPrefix);
Path tmpFile1 = Files.createTempFile(
tmpDir, customFilePrefix, customFileSuffix);
Path tmpFile2 = Files.createTempFile(
tmpDir, customFilePrefix, customFileSuffix);

Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try (DirectoryStream<Path> ds
= Files.newDirectoryStream(tmpDir)) {
for (Path file: ds) {
Files.delete(file);
}

Files.delete(tmpDir);
} catch (IOException e) {
...
}
}
});

//simulate some operations with temp file until delete it
Thread.sleep(10000);
} catch (IOException | InterruptedException e) {
...
}
A shutdown-hook will not be executed in the case of abnormal/forced terminations (for example, JVM crashes, Terminal operations are triggered, and so on). It runs when all the threads finish or when System.exit(0) is called. It is advisable to run it fast since they can be forcibly stopped before completion if something goes wrong (for example, the OS shuts down). Programmatically, a shutdown-hook can only be stopped by Runtime.halt().
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.170.187