-
Notifications
You must be signed in to change notification settings - Fork 478
Expand file tree
/
Copy pathChronicleHashCloseOnExitHook.java
More file actions
88 lines (78 loc) · 3.44 KB
/
Copy pathChronicleHashCloseOnExitHook.java
File metadata and controls
88 lines (78 loc) · 3.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* Copyright 2013-2026 chronicle.software; SPDX-License-Identifier: Apache-2.0
*/
package net.openhft.chronicle.hash.impl;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.shutdown.PriorityHook;
import java.util.TreeMap;
import java.util.WeakHashMap;
final class ChronicleHashCloseOnExitHook {
private static WeakHashMap<VanillaChronicleHash<?, ?, ?, ?>.Identity, Long> maps = new WeakHashMap<>();
private static long order = 0;
static {
PriorityHook.add(80, ChronicleHashCloseOnExitHook::closeAll);
}
private ChronicleHashCloseOnExitHook() {
}
static synchronized void add(VanillaChronicleHash<?, ?, ?, ?> hash) {
if (maps == null)
throw new IllegalStateException("Shutdown in progress");
maps.put(hash.identity, order++);
}
static synchronized void remove(VanillaChronicleHash<?, ?, ?, ?> hash) {
if (maps == null)
return; // we are already in shutdown
maps.remove(hash.identity);
}
private static void closeAll() {
try {
WeakHashMap<VanillaChronicleHash<?, ?, ?, ?>.Identity, Long> maps;
synchronized (ChronicleHashCloseOnExitHook.class) {
maps = ChronicleHashCloseOnExitHook.maps;
ChronicleHashCloseOnExitHook.maps = null;
}
TreeMap<Long, VanillaChronicleHash<?, ?, ?, ?>> orderedMaps = new TreeMap<>();
maps.forEach((identity, order) -> orderedMaps.put(order, identity.hash()));
// close later added maps first
orderedMaps.descendingMap().values().forEach(h -> {
try {
Runnable preShutdownAction = h.getPreShutdownAction();
if (preShutdownAction != null) {
try {
preShutdownAction.run();
} catch (Throwable throwable) {
try {
Jvm.error().on(ChronicleHashCloseOnExitHook.class,
"Error running pre-shutdown action for " + h.toIdentityString() +
" :", throwable);
} catch (Throwable t2) {
throwable.addSuppressed(t2);
throwable.printStackTrace();
}
}
}
h.close();
} catch (Throwable throwable) {
try {
Jvm.error().on(ChronicleHashCloseOnExitHook.class,
"Error while closing " + h.toIdentityString() +
" during shutdown hook:", throwable);
} catch (Throwable t2) {
// This may occur if the log service has already been shut down. Try to fall
// back to printStackTrace().
throwable.addSuppressed(t2);
throwable.printStackTrace();
}
}
});
} catch (Throwable throwable) {
try {
Jvm.error().on(ChronicleHashCloseOnExitHook.class,
"Error while closing maps during shutdown hook:", throwable);
} catch (Throwable t2) {
throwable.addSuppressed(t2);
throwable.printStackTrace();
}
}
}
}