Path: blob/master/src/java.base/share/classes/java/io/DeleteOnExitHook.java
41152 views
/*1* Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package java.io;2526import java.util.*;2728import jdk.internal.access.SharedSecrets;2930/**31* This class holds a set of filenames to be deleted on VM exit through a shutdown hook.32* A set is used both to prevent double-insertion of the same file as well as offer33* quick removal.34*/3536class DeleteOnExitHook {37private static LinkedHashSet<String> files = new LinkedHashSet<>();38static {39// DeleteOnExitHook must be the last shutdown hook to be invoked.40// Application shutdown hooks may add the first file to the41// delete on exit list and cause the DeleteOnExitHook to be42// registered during shutdown in progress. So set the43// registerShutdownInProgress parameter to true.44SharedSecrets.getJavaLangAccess()45.registerShutdownHook(2 /* Shutdown hook invocation order */,46true /* register even if shutdown in progress */,47new Runnable() {48public void run() {49runHooks();50}51}52);53}5455private DeleteOnExitHook() {}5657static synchronized void add(String file) {58if(files == null) {59// DeleteOnExitHook is running. Too late to add a file60throw new IllegalStateException("Shutdown in progress");61}6263files.add(file);64}6566static void runHooks() {67LinkedHashSet<String> theFiles;6869synchronized (DeleteOnExitHook.class) {70theFiles = files;71files = null;72}7374ArrayList<String> toBeDeleted = new ArrayList<>(theFiles);7576// reverse the list to maintain previous jdk deletion order.77// Last in first deleted.78Collections.reverse(toBeDeleted);79for (String filename : toBeDeleted) {80(new File(filename)).delete();81}82}83}848586