forked from JetBrains/skija
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Managed.java
59 lines (49 loc) · 1.77 KB
/
Managed.java
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
package org.jetbrains.skija.impl;
import org.jetbrains.annotations.*;
import java.lang.ref.Cleaner;
public abstract class Managed extends Native implements AutoCloseable {
@ApiStatus.Internal
public Cleaner.Cleanable _cleanable;
public Managed(long ptr, long finalizer) {
this(ptr, finalizer, true);
}
public Managed(long ptr, long finalizer, boolean managed) {
super(ptr);
if (managed) {
assert ptr != 0 : "Managed ptr is 0";
assert finalizer != 0 : "Managed finalizer is 0";
String className = getClass().getSimpleName();
Stats.onAllocated(className);
this._cleanable = _cleaner.register(this, new CleanerThunk(className, ptr, finalizer));
}
}
@Override
public void close() {
if (0 == _ptr)
throw new RuntimeException("Object already closed: " + this);
else if (null == _cleanable)
throw new RuntimeException("Object is not managed in JVM, can't close(): " + this);
else {
_cleanable.clean();
_cleanable = null;
_ptr = 0;
}
}
public static Cleaner _cleaner = Cleaner.create();
public static class CleanerThunk implements Runnable {
public String _className;
public long _ptr;
public long _finalizerPtr;
public CleanerThunk(String className, long ptr, long finalizer) {
this._className = className;
this._ptr = ptr;
this._finalizerPtr = finalizer;
}
public void run() {
Stats.onDeallocated(_className);
Stats.onNativeCall();
_nInvokeFinalizer(_finalizerPtr, _ptr);
}
}
public static native void _nInvokeFinalizer(long finalizer, long ptr);
}