01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.util;
07:
08: import java.lang.ref.PhantomReference;
09: import java.lang.ref.Reference;
10: import java.lang.ref.ReferenceQueue;
11: import java.util.HashMap;
12:
13: import org.h2.constant.SysProperties;
14: import org.h2.message.Message;
15:
16: /**
17: * This class deletes temporary files when they are not used any longer.
18: */
19: public class TempFileDeleter {
20:
21: private static final ReferenceQueue QUEUE = new ReferenceQueue();
22: private static final HashMap REF_MAP = new HashMap();
23:
24: public static synchronized Reference addFile(String fileName,
25: Object file) {
26: FileUtils.trace("TempFileDeleter.addFile", fileName, file);
27: PhantomReference ref = new PhantomReference(file, QUEUE);
28: REF_MAP.put(ref, fileName);
29: deleteUnused();
30: return ref;
31: }
32:
33: public static synchronized void deleteFile(Reference ref,
34: String fileName) {
35: if (ref != null) {
36: String f2 = (String) REF_MAP.remove(ref);
37: if (SysProperties.CHECK && f2 != null && fileName != null
38: && !f2.equals(fileName)) {
39: throw Message.getInternalError("f2:" + f2 + " f:"
40: + fileName);
41: }
42: fileName = f2;
43: }
44: if (fileName != null && FileUtils.exists(fileName)) {
45: try {
46: FileUtils.trace("TempFileDeleter.deleteFile", fileName,
47: null);
48: FileUtils.tryDelete(fileName);
49: } catch (Exception e) {
50: // TODO log such errors?
51: }
52: }
53: }
54:
55: public static void deleteUnused() {
56: // Mystery: I don't know how QUEUE could get null, but two independent
57: // people reported NullPointerException here - if somebody understands
58: // how it could happen please report it!
59: // Environment: web application under Tomcat, exception occurs during undeploy
60: while (QUEUE != null) {
61: Reference ref = QUEUE.poll();
62: if (ref == null) {
63: break;
64: }
65: deleteFile(ref, null);
66: }
67: }
68:
69: public static void stopAutoDelete(Reference ref, String fileName) {
70: FileUtils
71: .trace("TempFileDeleter.stopAutoDelete", fileName, ref);
72: if (ref != null) {
73: String f2 = (String) REF_MAP.remove(ref);
74: if (SysProperties.CHECK
75: && (f2 == null || !f2.equals(fileName))) {
76: throw Message.getInternalError("f2:" + f2 + " f:"
77: + fileName);
78: }
79: }
80: deleteUnused();
81: }
82:
83: }
|