Use the Runnable.run method to clean direct byte buffers if avaiable.

Motivation:

In JDK9 the Cleaner.clean method cannot be called as it is not exported
from `java.base`. `Runnable.run` should be called instead.

Modifications:
Pick Runnable.run if the cleaner implements Runnable. Otherwise try the
clean method on the class implementing the cleaner.

Result:
The cleaner for direct byte buffers is run on JDK9 as well as earlier
JDKs.
This commit is contained in:
Carsten Varming 2016-07-14 15:32:54 -04:00 committed by Norman Maurer
parent f04ff5b715
commit cb071910ba
1 changed files with 10 additions and 3 deletions

View File

@ -31,10 +31,17 @@ public final class ByteBufferUtil {
Method directBufferCleanerCleanX = null;
boolean v;
try {
directBufferCleanerX = Class.forName("java.nio.DirectByteBuffer").getMethod("cleaner");
ByteBuffer direct = ByteBuffer.allocateDirect(1);
directBufferCleanerX = direct.getClass().getMethod("cleaner");
directBufferCleanerX.setAccessible(true);
directBufferCleanerCleanX = Class.forName("sun.misc.Cleaner").getMethod("clean");
directBufferCleanerCleanX.setAccessible(true);
Object cleaner = directBufferCleanerX.invoke(direct);
try {
Runnable runnable = (Runnable) cleaner;
directBufferCleanerCleanX = Runnable.class.getDeclaredMethod("run");
} catch (ClassCastException ignored) {
directBufferCleanerCleanX = cleaner.getClass().getMethod("clean");
}
directBufferCleanerCleanX.invoke(cleaner);
v = true;
} catch (Exception e) {
v = false;