What's the proper way to clean a DirectByteBuffer? In Java 8 you could do
void clean(DirectByteBuffer dbb) {
Cleaner cleaner = dbb.cleaner();
if (cleaner != null) {
cleaner.clean();
}
}
Currently I'm using sun.misc.Unsafe
void clean(DirectByteBuffer dbb) {
Unsafe unsafe = myGetUnsafe();
unsafe.invokeCleaner(dbb);
}
But I don't believe that's the correct way to go about it. I know java.lang.ref.Cleaner exists, but I couldn't get it working with this. I had something like
void clean(DirectByteBuffer dbb) {
Cleaner cleaner = Cleaner.create();
cleaner.register(dbb, new Runnable() {
public void run() {
Cleaner cleaner = dbb.cleaner();
if (cleaner != null) {
cleaner.clean();
}
}
});
}
I thought the later would work because the Runnable is invoked by internal JDK stuff which would mean that since it's within the same module, this would be allowed, but I'm getting IllegalAccessException here.
So what's the correct way to clean a DirectByteBuffer object in JDK 11+?