package net.openhft.chronicle.core.cleaner.impl.jdk9;

import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.UnsafeMemory;
import net.openhft.chronicle.core.annotation.TargetMajorVersion;
import net.openhft.chronicle.core.cleaner.spi.ByteBufferCleanerService;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.ByteBuffer;

@TargetMajorVersion(majorVersion = 9)
public final class Jdk9ByteBufferCleanerService implements ByteBufferCleanerService {
    private static final MethodHandle invokeCleanerMethod = getInvokeCleanerMethod();

    private static MethodHandle getInvokeCleanerMethod() {
        MethodType signature = MethodType.methodType(void.class, ByteBuffer.class);
        try {
            return MethodHandles.publicLookup().findVirtual(UnsafeMemory.UNSAFE.getClass(), "invokeCleaner", signature);
        } catch (NoSuchMethodException | IllegalAccessException e) {
            if (Jvm.isJava9Plus()) {
                throw new ExceptionInInitializerError(e);
            }
            return null;
        }
    }

    @Override
    public void clean(final ByteBuffer buffer) {
        try {
            invokeCleanerMethod.invokeExact(UnsafeMemory.UNSAFE, buffer);
        } catch (Throwable throwable) {
            Jvm.rethrow(throwable);
        }
    }

    @Override
    public int impact() {
        // invokeExact() + `static final` method handle = inlined to vanilla method call
        return NO_IMPACT;
    }
}

@@ -586,24 +586,25 @@
 nvokeCleaner
+_
 Method = get
@@ -599,25 +599,26 @@
 Method = get
-I
+_i
 nvokeCleaner
@@ -609,32 +609,33 @@
 et_invokeCleaner
+_
 Method();%0A%0A    p
@@ -664,17 +664,18 @@
 ndle get
-I
+_i
 nvokeCle
@@ -674,24 +674,25 @@
 nvokeCleaner
+_
 Method() %7B%0A 
@@ -686,24 +686,174 @@
 _Method() %7B%0A
+        if (!Jvm.isJava9Plus()) %7B%0A            return null;%0A        %7D%0A        // Access invokeCleaner() reflectively to support compilation with JDK 8%0A
         Meth
@@ -1132,49 +1132,8 @@
 ) %7B%0A
-            if (Jvm.isJava9Plus()) %7B%0A    
     
@@ -1186,47 +1186,8 @@
 e);%0A
-            %7D%0A            return null;%0A
     
@@ -1301,16 +1301,17 @@
 eCleaner
+_
 Method.i
@@ -1513,9 +1513,10 @@
 t() 
-+
+on
  %60st
@@ -1541,17 +1541,18 @@
  handle 
-=
+is
  inlined

Improve code