Debian Codegraph @

src/main/org/h2/engine/DelayedDatabaseCloser.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.engine;
7
8 import java.lang.ref.WeakReference;
9
10 import org.h2.message.Trace;
11
12 /**
13 * This class is responsible to close a database after the specified delay. A
14 * database closer object only exists if there is no user connected to the
15 * database.
16 */
17 class DelayedDatabaseCloser extends Thread {
18
19 private final Trace trace;
20 private volatile WeakReference<Database> databaseRef;
21 private int delayInMillis;
22
23 DelayedDatabaseCloser(Database db, int delayInMillis) {
24 databaseRef = new WeakReference<>(db);
25 this.delayInMillis = delayInMillis;
26 trace = db.getTrace(Trace.DATABASE);
27 setName("H2 Close Delay " + db.getShortName());
28 setDaemon(true);
29 start();
30 }
31
32 /**
33 * Stop and disable the database closer. This method is called after a session
34 * has been created.
35 */
36 void reset() {
37 databaseRef = null;
38 }
39
40 @Override
41 public void run() {
42 while (delayInMillis > 0) {
43 try {
44 int step = 100;
45 Thread.sleep(step);
46 delayInMillis -= step;
47 } catch (Exception e) {
48 // ignore InterruptedException
49 }
50 WeakReference<Database> ref = databaseRef;
51 if (ref == null || ref.get() == null) {
52 return;
53 }
54 }
55 Database database;
56 WeakReference<Database> ref = databaseRef;
57 if (ref != null && (database = ref.get()) != null) {
58 try {
59 database.close(false);
60 } catch (RuntimeException e) {
61 // this can happen when stopping a web application,
62 // if loading classes is no longer allowed
63 // it would throw an IllegalStateException
64 try {
65 trace.error(e, "could not close the database");
66 // if this was successful, we ignore the exception
67 // otherwise not
68 } catch (Throwable e2) {
69 e.addSuppressed(e2);
70 throw e;
71 }
72 }
73 }
74 }
75
76 }