如何在Java中监视直接内存

时间:2017-05-15 06:45:36

标签: java monitor

如何监控Java中的直接内存(Off heap memory), 直接通过Unsafe类分配内存

class Unsafe {    public native long allocateMemory(long var1) }

我使用net.openhft.chronicle.map.ChronicleMap技术,它在内部调用Unsafe,我想实时监控内存的大小,但它不提供api

package org.x.server.es.plugins.offheap.map;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Set;
import sun.misc.Unsafe;
public class TestDirectMemory {
    public static void main(String[] args) throws IllegalArgumentException, 
    IllegalAccessException, InterruptedException {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe)unsafeField.get(null);
        Set<ByteBuffer> set = new HashSet<>();
        while(true) {
            long address = unsafe.allocateMemory(1024 * 1024 * 100);
            unsafe.setMemory(address, 1024 * 1024 * 100, (byte)0);
            System.out.println(sun.misc.SharedSecrets.getJavaNioAccess().getDirectBufferPool().getMemoryUsed());
            System.out.println(sun.misc.VM.maxDirectMemory());
//          ByteBuffer bb = ByteBuffer.allocateDirect(1024*1024);
//          set.add(bb);
//          for (int i = 0; i < 1024*1024; i++){
//              bb.put((byte)0);
//          }
            Thread.sleep(5000);
            System.out.println("^^^^^^^^^^^");
        }
    }
}

0 个答案:

没有答案