Created
June 1, 2016 01:00
-
-
Save ztellman/3a4fcef2291151bea809184b8c5410a9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class Netty { | |
private Netty() { | |
} | |
private static final Field QUEUE; | |
private static final Class BITS; | |
private static final Class VM; | |
private static final Field RESERVED_MEMORY; | |
private static final Method MAX_DIRECT_MEMORY; | |
static { | |
try { | |
QUEUE = SingleThreadEventExecutor.class.getDeclaredField("taskQueue"); | |
QUEUE.setAccessible(true); | |
BITS = Class.forName("java.nio.Bits"); | |
RESERVED_MEMORY = BITS.getDeclaredField("reservedMemory"); | |
RESERVED_MEMORY.setAccessible(true); | |
VM = Class.forName("sun.misc.VM"); | |
MAX_DIRECT_MEMORY = VM.getDeclaredMethod("maxDirectMemory"); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* @param executor a Netty event executor | |
* @param lengthCallback a callback which accepts the executor's queue length | |
* @param latencyCallback a callback which accepts the executor's latency, in nanoseconds | |
*/ | |
public static void sampleQueue( | |
final EventExecutor executor, | |
final Consumer<Integer> lengthCallback, | |
final Consumer<Long> latencyCallback) { | |
if (executor.isShutdown()) { | |
return; | |
} | |
executor.execute(() -> { | |
try { | |
lengthCallback.accept(((Queue) QUEUE.get(executor)).size()); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
final long start = System.nanoTime(); | |
executor.execute(() -> latencyCallback.accept(System.nanoTime() - start)); | |
}); | |
} | |
/** | |
* @return the size, in bytes, of the off-heap memory usage. | |
*/ | |
public static long numOffHeapBytes() { | |
try { | |
return (long) RESERVED_MEMORY.get(BITS); | |
} catch (Throwable e) { | |
return 0; | |
} | |
} | |
/** | |
* @return the maximum size, in bytes, of the allocated off-heap memory. | |
*/ | |
public static long maxOffHeapBytes() { | |
try { | |
return (long) MAX_DIRECT_MEMORY.invoke(VM); | |
} catch (Throwable e) { | |
return Long.MAX_VALUE; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment