我试图在我的生产应用程序中找到本机内存泄漏。问题是要知道我的代码中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
并且我有一个根据此说明获得的 .gif 文件。我有一张图片
那我怎么能猜到,那0x00007f2e42297ea7
是useWithLeak
方法?这是真的吗?