KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > io > DeleteOnExitHook


1 /*
2  * @(#)DeleteOnExitHook.java 1.4 06/06/20
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package java.io;
8
9 import java.util.*;
10 import java.io.File JavaDoc;
11
12 /**
13  * This class holds a set of filenames to be deleted on VM exit through a shutdown hook.
14  * A set is used both to prevent double-insertion of the same file as well as offer
15  * quick removal.
16  */

17
18 class DeleteOnExitHook {
19     private static DeleteOnExitHook JavaDoc instance = null;
20
21     private static LinkedHashSet<String JavaDoc> files = new LinkedHashSet<String JavaDoc>();
22
23     static DeleteOnExitHook JavaDoc hook() {
24     if (instance == null)
25         instance = new DeleteOnExitHook JavaDoc();
26
27     return instance;
28     }
29
30     private DeleteOnExitHook() {}
31
32     static void add(String JavaDoc file) {
33     synchronized(files) {
34         if(files == null)
35         throw new IllegalStateException JavaDoc("Shutdown in progress");
36
37         files.add(file);
38     }
39     }
40
41     void run() {
42     LinkedHashSet<String JavaDoc> theFiles;
43
44     synchronized (files) {
45         theFiles = files;
46         files = null;
47     }
48
49     ArrayList<String JavaDoc> toBeDeleted = new ArrayList<String JavaDoc>(theFiles);
50
51     // reverse the list to maintain previous jdk deletion order.
52
// Last in first deleted.
53
Collections.reverse(toBeDeleted);
54     for (String JavaDoc filename : toBeDeleted) {
55         (new File JavaDoc(filename)).delete();
56     }
57     }
58 }
59
60
Popular Tags