in common/src/main/java/org/mvndaemon/mvnd/common/BufferHelper.java [138:234]
private static boolean closeDirectByteBufferPrivileged(final ByteBuffer byteBuffer, final Consumer<String> log) {
if (!byteBuffer.isDirect()) {
// Nothing to do
return true;
}
try {
if (PRE_JAVA_9) {
if (attachmentMethod == null) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, attachmentMethod == null");
}
return false;
}
// Make sure duplicates and slices are not cleaned, since this can result in duplicate
// attempts to clean the same buffer, which trigger a crash with:
// "A fatal error has been detected by the Java Runtime Environment: EXCEPTION_ACCESS_VIOLATION"
// See: https://stackoverflow.com/a/31592947/3950982
if (attachmentMethod.invoke(byteBuffer) != null) {
// Buffer is a duplicate or slice
return false;
}
// Invoke ((DirectBuffer) byteBuffer).cleaner().clean()
if (directByteBufferCleanerMethod == null) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, cleanerMethod == null");
}
return false;
}
try {
directByteBufferCleanerMethod.setAccessible(true);
} catch (final Exception e) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, cleanerMethod.setAccessible(true) failed");
}
return false;
}
final Object cleanerInstance = directByteBufferCleanerMethod.invoke(byteBuffer);
if (cleanerInstance == null) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, cleaner == null");
}
return false;
}
if (cleanerCleanMethod == null) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, cleanMethod == null");
}
return false;
}
try {
cleanerCleanMethod.invoke(cleanerInstance);
return true;
} catch (final Exception e) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, cleanMethod.invoke(cleaner) failed: " + e);
}
return false;
}
// } else if (memorySegmentOfByteBufferMethod != null) {
// // JDK 14+
// final Object memorySegment = memorySegmentOfByteBufferMethod.invoke(null, byteBuffer);
// if (memorySegment == null) {
// if (log != null) {
// log.log("Got null MemorySegment, could not unmap ByteBuffer");
// }
// return false;
// }
// memorySegmentCloseMethod.invoke(memorySegment);
// return true;
} else {
if (theUnsafe == null) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, theUnsafe == null");
}
return false;
}
if (cleanerCleanMethod == null) {
if (log != null) {
log.accept("Could not unmap ByteBuffer, cleanMethod == null");
}
return false;
}
try {
cleanerCleanMethod.invoke(theUnsafe, byteBuffer);
return true;
} catch (final IllegalArgumentException e) {
// Buffer is a duplicate or slice
return false;
}
}
} catch (final ReflectiveOperationException | SecurityException e) {
if (log != null) {
log.accept("Could not unmap ByteBuffer: " + e);
}
return false;
}
}