KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > util > TempFileDeleter


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.util;
6
7 import java.lang.ref.PhantomReference JavaDoc;
8 import java.lang.ref.Reference JavaDoc;
9 import java.lang.ref.ReferenceQueue JavaDoc;
10 import java.util.HashMap JavaDoc;
11
12 import org.h2.engine.Constants;
13 import org.h2.message.Message;
14
15 public class TempFileDeleter {
16
17     private static ReferenceQueue JavaDoc queue = new ReferenceQueue JavaDoc();
18     private static HashMap JavaDoc refMap = new HashMap JavaDoc();
19
20     public static synchronized Reference JavaDoc addFile(String JavaDoc fileName, Object JavaDoc file) {
21         PhantomReference JavaDoc ref = new PhantomReference JavaDoc(file, queue);
22         refMap.put(ref, fileName);
23         deleteUnused();
24         return ref;
25     }
26
27     public static synchronized void deleteFile(Reference JavaDoc ref, String JavaDoc fileName) {
28         if(ref != null) {
29             String JavaDoc f2 = (String JavaDoc) refMap.remove(ref);
30             if(Constants.CHECK && f2 != null && fileName != null && !f2.equals(fileName)) {
31                 throw Message.getInternalError("f2:"+f2+" f:"+fileName);
32             }
33         }
34         if(fileName != null && FileUtils.exists(fileName)) {
35             try {
36                 FileUtils.delete(fileName);
37             } catch(Exception JavaDoc e) {
38                 // TODO log such errors?
39
}
40         }
41         deleteUnused();
42     }
43     
44     public static void deleteUnused() {
45         while(true) {
46             Reference JavaDoc ref = queue.poll();
47             if(ref == null) {
48                 break;
49             }
50             deleteFile(ref, null);
51         }
52     }
53
54     public static void stopAutoDelete(Reference JavaDoc ref, String JavaDoc fileName) {
55         if(ref != null) {
56             String JavaDoc f2 = (String JavaDoc) refMap.remove(ref);
57             if(Constants.CHECK && (f2 == null || !f2.equals(fileName))) {
58                 throw Message.getInternalError("f2:"+f2+" f:"+fileName);
59             }
60         }
61         deleteUnused();
62     }
63
64 }
65
Popular Tags