观察NIO的direct memory使用量?
前几天有同事问起,我本来印象中是有啥别的办法的,但想不起来了。
再看了看NIO相关部分的源码觉得貌似就这个办法靠谱(在Oracle/Sun的JDK上):
StackOverflow: Looking up how much direct buffer memory is available to Java?
通过反射获取java.nio.Bits类里的maxMemory与reservedMemory字段来达到观察的目的。
用Groovy演示一下:
D:\sdk\groovy-1.7.6\bin>groovyshGroovy Shell (1.7.6, JVM: 1.6.0_26)Type 'help' or '\h' for help.-------------------------------------------groovy:000> import java.nio.*===> [import java.nio.*]groovy:000> Bits.reservedMemory===> 0groovy:000> Bits.maxMemory===> 67108864groovy:000> buf = ByteBuffer.allocateDirect(4096)===> java.nio.DirectByteBuffer[pos=0 lim=4096 cap=4096]groovy:000> Bits.reservedMemory===> 4096groovy:000> Bits.maxMemory===> 129761280groovy:000> buf.direct===> truegroovy:000> buf.hasArray()===> falsegroovy:000> buf.cleaner().clean()===> nullgroovy:000> Bits.reservedMemory===> 0groovy:000> Bits.maxMemory===> 129761280groovy:000> quit