Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/io/DeleteOnExitHook.java
38829 views
/*1* Copyright (c) 2005, 2010, 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.*;27import java.io.File;2829/**30* This class holds a set of filenames to be deleted on VM exit through a shutdown hook.31* A set is used both to prevent double-insertion of the same file as well as offer32* quick removal.33*/3435class DeleteOnExitHook {36private static LinkedHashSet<String> files = new LinkedHashSet<>();37static {38// DeleteOnExitHook must be the last shutdown hook to be invoked.39// Application shutdown hooks may add the first file to the40// delete on exit list and cause the DeleteOnExitHook to be41// registered during shutdown in progress. So set the42// registerShutdownInProgress parameter to true.43sun.misc.SharedSecrets.getJavaLangAccess()44.registerShutdownHook(2 /* Shutdown hook invocation order */,45true /* register even if shutdown in progress */,46new Runnable() {47public void run() {48runHooks();49}50}51);52}5354private DeleteOnExitHook() {}5556static synchronized void add(String file) {57if(files == null) {58// DeleteOnExitHook is running. Too late to add a file59throw new IllegalStateException("Shutdown in progress");60}6162files.add(file);63}6465static void runHooks() {66LinkedHashSet<String> theFiles;6768synchronized (DeleteOnExitHook.class) {69theFiles = files;70files = null;71}7273ArrayList<String> toBeDeleted = new ArrayList<>(theFiles);7475// reverse the list to maintain previous jdk deletion order.76// Last in first deleted.77Collections.reverse(toBeDeleted);78for (String filename : toBeDeleted) {79(new File(filename)).delete();80}81}82}838485