Skip to content

Commit

Permalink
Just cast Cleaner to Runnable in Java9+ to prevent IllegalAccessExcep…
Browse files Browse the repository at this point in the history
…tion

Motivation:

When try to call Cleaner.run() via reflection on Java9 you may see an IllegalAccessException.

Modifications:

Just cast the Cleaner to Runnable to prevent IllegalAccessException to be raised.

Result:

Free direct buffers also work on Java9+ as expected.
  • Loading branch information
normanmaurer committed Aug 11, 2016
1 parent cb5f717 commit be77dfb
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions common/src/main/java/io/netty/util/internal/Cleaner0.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,16 @@
final class Cleaner0 {
private static final long CLEANER_FIELD_OFFSET;
private static final Method CLEAN_METHOD;
private static final boolean CLEANER_IS_RUNNABLE;

private static final InternalLogger logger = InternalLoggerFactory.getInstance(Cleaner0.class);

static {
ByteBuffer direct = ByteBuffer.allocateDirect(1);
Field cleanerField;
long fieldOffset = -1;
Method clean = null;
boolean cleanerIsRunnable = false;
if (PlatformDependent0.hasUnsafe()) {
try {
cleanerField = direct.getClass().getDeclaredField("cleaner");
Expand All @@ -48,20 +51,23 @@ final class Cleaner0 {
try {
// Cleaner implements Runnable from JDK9 onwards.
Runnable runnable = (Runnable) cleaner;
clean = Runnable.class.getDeclaredMethod("run");
runnable.run();
cleanerIsRunnable = true;
} catch (ClassCastException ignored) {
clean = cleaner.getClass().getDeclaredMethod("clean");
clean.invoke(cleaner);
}
clean.invoke(cleaner);
} catch (Throwable t) {
// We don't have ByteBuffer.cleaner().
fieldOffset = -1;
clean = null;
cleanerIsRunnable = false;
}
}
logger.debug("java.nio.ByteBuffer.cleaner(): {}", fieldOffset != -1? "available" : "unavailable");
CLEANER_FIELD_OFFSET = fieldOffset;
CLEAN_METHOD = clean;
CLEANER_IS_RUNNABLE = cleanerIsRunnable;

// free buffer if possible
freeDirectBuffer(direct);
Expand All @@ -71,11 +77,16 @@ static void freeDirectBuffer(ByteBuffer buffer) {
if (CLEANER_FIELD_OFFSET == -1 || !buffer.isDirect()) {
return;
}
assert CLEAN_METHOD != null : "CLEANER_FIELD_OFFSET != -1 implies CLEAN_METHOD != null";
assert CLEAN_METHOD != null || CLEANER_IS_RUNNABLE:
"CLEANER_FIELD_OFFSET != -1 implies CLEAN_METHOD != null or CLEANER_IS_RUNNABLE == true";
try {
Object cleaner = PlatformDependent0.getObject(buffer, CLEANER_FIELD_OFFSET);
if (cleaner != null) {
CLEAN_METHOD.invoke(cleaner);
if (CLEANER_IS_RUNNABLE) {
((Runnable) cleaner).run();
} else {
CLEAN_METHOD.invoke(cleaner);
}
}
} catch (Throwable t) {
// Nothing we can do here.
Expand Down

0 comments on commit be77dfb

Please sign in to comment.