1 /* 2 * Copyright 2020 The Netty Project 3 * 4 * The Netty Project licenses this file to you under the Apache License, 5 * version 2.0 (the "License"); you may not use this file except in compliance 6 * with the License. You may obtain a copy of the License at: 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations 14 * under the License. 15 */ 16 package io.netty.handler.codec.http.multipart; 17 18 import java.io.File; 19 import java.util.Set; 20 import java.util.concurrent.ConcurrentHashMap; 21 22 /** 23 * DeleteFileOnExitHook. 24 */ 25 final class DeleteFileOnExitHook { 26 private static final Set<String> FILES = ConcurrentHashMap.newKeySet(); 27 28 private DeleteFileOnExitHook() { 29 } 30 31 static { 32 // DeleteOnExitHook must be the last shutdown hook to be invoked. 33 // Application shutdown hooks may add the first file to the 34 // delete on exit list and cause the DeleteOnExitHook to be 35 // registered during shutdown in progress. 36 Runtime.getRuntime().addShutdownHook(new Thread() { 37 38 @Override 39 public void run() { 40 runHook(); 41 } 42 }); 43 } 44 45 /** 46 * Remove from the pool to reduce space footprint. 47 * 48 * @param file tmp file path 49 */ 50 public static void remove(String file) { 51 FILES.remove(file); 52 } 53 54 /** 55 * Add to the hook and clean up when the program exits. 56 * 57 * @param file tmp file path 58 */ 59 public static void add(String file) { 60 FILES.add(file); 61 } 62 63 /** 64 * Check in the hook files. 65 * 66 * @param file target file 67 * @return true or false 68 */ 69 public static boolean checkFileExist(String file) { 70 return FILES.contains(file); 71 } 72 73 /** 74 * Clean up all the files. 75 */ 76 static void runHook() { 77 for (String filename : FILES) { 78 new File(filename).delete(); 79 } 80 } 81 }