如何找到调用不安全分配的方法?

时间:2019-01-17 14:13:39

标签: java allocation jemalloc

我正在尝试在生产应用程序中发现本机内存泄漏。问题是要知道我的代码中哪种方法unsafe.allocateMemory(size)不用unsafe.freeMemory(startIndex)

这适用于Ubuntu 18.04,Java版本为“ 1.8.0_191”。

// Example of "Unlimited array" 
class DirectIntArray implements Closeable {

    private final static long INT_SIZE_IN_BYTES = 4;

    private final long startIndex;

    private final Unsafe unsafe;

    public DirectIntArray(long size) throws NoSuchFieldException, IllegalAccessException {
        unsafe = getUnsafe();
        startIndex = unsafe.allocateMemory(size * INT_SIZE_IN_BYTES);
        unsafe.setMemory(startIndex, size * INT_SIZE_IN_BYTES, (byte) 0);
    }

    @Override
    public void close() throws IOException {
        unsafe.freeMemory(startIndex);
    }

    public void setValue(long index, int value) {
        unsafe.putInt(index(index), value);
    }

    public int getValue(long index) {
        return unsafe.getInt(index(index));
    }

    private long index(long offset) {
        return startIndex + offset * INT_SIZE_IN_BYTES;
    }

    private static Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        return (Unsafe) theUnsafe.get(null);
    }
} 



public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InterruptedException {

        int cnt = 0;
        System.out.println("Use big array in off-heap without freeing memory");
        while (true) {
            useWithLeak(MB);
            Thread.sleep(10);
            System.out.println(++cnt + "MB Allocated");
        }
    }

    public static void useWithLeak(long len) {
        try {
            DirectIntArray arr = new DirectIntArray(len);
            arr.setValue(1, 111);
            arr.setValue(len, 222);

            System.out.println("Read from off-heap values: " +  arr.getValue(1) + ", " + arr.getValue(len));
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

因此,我编写了执行本机内存泄漏的代码,并且我想找到一种执行此操作的方法。我使用jemalloc,并且有一个根据此instruction获得的.gif文件。我有一张图片

enter image description here

那么我怎么猜0x00007f2e42297ea7useWithLeak方法呢?是真的吗?

0 个答案:

没有答案