forked from ScottOaks/JavaPerformanceTuning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCleanupClass.java
More file actions
72 lines (61 loc) · 2 KB
/
Copy pathCleanupClass.java
File metadata and controls
72 lines (61 loc) · 2 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
/*
* Copyright (c) 2013,2014 Scott Oaks. All rights reserved.
*/
package net.sdo;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CleanupClass {
private static class CleanupFinalizer extends WeakReference {
private static ReferenceQueue<CleanupFinalizer> finRefQueue;
private static HashSet<CleanupFinalizer> pendingRefs = new HashSet<>();
static {
finRefQueue = new ReferenceQueue<>();
Runnable r = new Runnable() {
@Override
public void run() {
CleanupFinalizer fr;
while (true) {
try {
fr = (CleanupFinalizer) finRefQueue.remove();
fr.cleanup();
pendingRefs.remove(fr);
} catch (Exception ex) {
ex.printStackTrace();
Logger.getLogger(CleanupFinalizer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
Thread t = new Thread(r);
t.setDaemon(true);
t.start();
}
private boolean closed = false;
public CleanupFinalizer(Object o) {
super(o, finRefQueue);
pendingRefs.add(this);
}
public void setClosed() {
System.out.println("Called setClose for " + this);
closed = true;
doNativeCleanup();
}
public void cleanup() {
if (!closed) {
System.out.println("Called cleanup for " + this);
doNativeCleanup();
}
}
private void doNativeCleanup() {}
}
CleanupFinalizer cf;
public CleanupClass() {
cf = new CleanupFinalizer(this);
}
public void close() {
cf.setClosed();
}
}