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.engine;
07:
08: import java.lang.ref.WeakReference;
09:
10: /**
11: * This class is responsible to close a database if the application did not
12: * close a connection.
13: */
14: public class DatabaseCloser extends Thread {
15:
16: private final boolean shutdownHook;
17: private volatile WeakReference databaseRef;
18: private int delayInMillis;
19: private boolean stopImmediately;
20:
21: DatabaseCloser(Database db, int delayInMillis, boolean shutdownHook) {
22: this .databaseRef = new WeakReference(db);
23: this .delayInMillis = delayInMillis;
24: this .shutdownHook = shutdownHook;
25: }
26:
27: public void reset() {
28: synchronized (this ) {
29: databaseRef = null;
30: }
31: if (getThreadGroup().activeCount() > 100) {
32: // in JDK 1.4 and below, all Thread objects are added to the ThreadGroup,
33: // and cause a memory leak if never started.
34: // Need to start it, otherwise it leaks memory in JDK 1.4 and below
35: stopImmediately = true;
36: try {
37: start();
38: } catch (Throwable e) {
39: // ignore
40: }
41: }
42: }
43:
44: public void run() {
45: if (stopImmediately) {
46: return;
47: }
48: while (delayInMillis > 0) {
49: try {
50: int step = 100;
51: Thread.sleep(step);
52: delayInMillis -= step;
53: } catch (Exception e) {
54: // ignore
55: }
56: if (databaseRef == null) {
57: return;
58: }
59: }
60: Database database = null;
61: synchronized (this ) {
62: if (databaseRef != null) {
63: database = (Database) databaseRef.get();
64: }
65: }
66: if (database != null) {
67: database.close(shutdownHook);
68: }
69: }
70:
71: }
|