概念
JVM可以使用的内存分外2种:堆内存和堆外内存。
堆内存
由JVM负责分配和释放,如果程序没有缺陷代码导致内存泄露,那么就不会遇到java.lang.OutOfMemoryError(OOM)
这个错误。
堆外内存
直接分配和释放内存,提高效率。堆外内存意味着把内存对象分配在Java虚拟机的堆以外的内存,这些内存直接受操作系统管理(而不是虚拟机)。这样做的结果就是能保持一个较小的堆,以减少垃圾收集对应用的影响。JDK5.0之后,代码中能直接操作本地内存的方式有2种:使用未公开的Unsafe
和NIO
的ByteBuffer
。存储对象生命周期比较长,对象数据结构比较单一。
堆外内存优点
- 可以扩展至更大的内存空间。
- 理论上能减少GC暂停时间。因为垃圾回收会暂停其他的工作。
- 可以在进程间共享,减少JVM间的对象复制,使得JVM的分割部署更容易实现。因为堆内在flush到远程时,会先复制到直接内存(非堆内存),然后在发送;而堆外内存相当于省略掉了这个工作。
- 它的持久化存储可以支持快速重启,同时还能够在测试环境中重现生产数据。
堆外内存缺点
- 堆外内存难以控制,如果内存泄漏,那么很难排查。
- 数据结构不能复杂化,结构单一,最好是基础类型。使用序列化和反序列化,性能比堆内对象还差。
- 使用堆外内存,不用考虑JVM内存限制,但需要考虑磁盘系统。(HDD或者SSD)
堆外内存释放
ByteBuffer
ByteBuffer.allocateDirect
分配的堆外内存不需要我们手动释放,GC会自己执行,而且ByteBuffer
中也没有提供手动释放的API。也即是说,使用ByteBuffer
不用担心堆外内存的释放问题,除非堆内存中的ByteBuffer
对象由于错误编码而出现内存泄露。
ByteBuffer#allocateDirect()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19/**
* Allocates a new direct byte buffer.
*
* <p> The new buffer's position will be zero, its limit will be its
* capacity, its mark will be undefined, and each of its elements will be
* initialized to zero. Whether or not it has a
* {@link #hasArray </code>backing array<code>} is unspecified.
*
* @param capacity
* The new buffer's capacity, in bytes
*
* @return The new byte buffer
*
* @throws IllegalArgumentException
* If the <tt>capacity</tt> is a negative integer
*/
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity);
}
测试程序1
2
3
4
5public static void main(String[] args) throws Exception {
while (true) {
ByteBuffer buffer = ByteBuffer.allocateDirect(10 * 1024 * 1024);
}
}
在Eclipse里设置
- 打印GC日志:
-verbose:gc -XX:+PrintGCDetails
- 设置堆外内存:
-XX:MaxDirectMemorySize=40M
- 禁止调用GC:
-XX:+DisableExplicitGC
1 | -verbose:gc -XX:+PrintGCDetails -XX:MaxDirectMemorySize=40M |
ByteBuffer释放堆外内存,源码查看
ByteBuffer.allocateDirect(10 * 1024 * 1024)
分配内存,进入 DirectByteBuffer(int cap)
,此方法里有调用这个方法 Bits.reserveMemory(size, cap)
,这个方法是分配内存和释放垃圾对象。该方法里先执行内存分配,然后释放垃圾对象,进行GC;这个方法后面有段代码cleaner = Cleaner.create(this, new Deallocator(base, size, cap))
,这个是创建清理外部内存线程的方法,new Deallocator(base, size, cap)
是一个任务实例。
DirectByteBuffer#DirectByteBuffer1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24DirectByteBuffer(int cap) { // package-private
super(-1, 0, cap, cap);
boolean pa = VM.isDirectMemoryPageAligned();
int ps = Bits.pageSize();
long size = Math.max(1L, (long)cap + (pa ? ps : 0));
Bits.reserveMemory(size, cap);
long base = 0;
try {
base = unsafe.allocateMemory(size);
} catch (OutOfMemoryError x) {
Bits.unreserveMemory(size, cap);
throw x;
}
unsafe.setMemory(base, size, (byte) 0);
if (pa && (base % ps != 0)) {
// Round up to page boundary
address = base + ps - (base & (ps - 1));
} else {
address = base;
}
cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
att = null;
}
DirectByteBuffer#Deallocator1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27private static class Deallocator implements Runnable
{
private static Unsafe unsafe = Unsafe.getUnsafe();
private long address;
private long size;
private int capacity;
private Deallocator(long address, long size, int capacity) {
assert (address != 0);
this.address = address;
this.size = size;
this.capacity = capacity;
}
public void run() {
if (address == 0) {
// Paranoia
return;
}
unsafe.freeMemory(address);
address = 0;
Bits.unreserveMemory(size, capacity);
}
}
DirectByteBuffer#reserveMemory1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33static void reserveMemory(long size, int cap) {
synchronized (Bits.class) {
if (!memoryLimitSet && VM.isBooted()) {
maxMemory = VM.maxDirectMemory();
memoryLimitSet = true;
}
// -XX:MaxDirectMemorySize limits the total capacity rather than the
// actual memory usage, which will differ when buffers are page
// aligned.
if (cap <= maxMemory - totalCapacity) {
reservedMemory += size;
totalCapacity += cap;
count++;
return;
}
}
System.gc();
try {
Thread.sleep(100);
} catch (InterruptedException x) {
// Restore interrupt status
Thread.currentThread().interrupt();
}
synchronized (Bits.class) {
if (totalCapacity + cap > maxMemory)
throw new OutOfMemoryError("Direct buffer memory");
reservedMemory += size;
totalCapacity += cap;
count++;
}
}
Unsafe
Unsafe
分配内存,需要手动去释放内存,不然会报OOM
错。使用Unsafe
是有风险的,很容易导致内存泄露。1
2
3
4
5
6
7
8
9
10
11
12
13public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// 通过反射获取rt.jar下的Unsafe类
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
// 实例化对象
Unsafe unsafe = (Unsafe) field.get(null);
while (true) {
long pointer = unsafe.allocateMemory(1024 * 1024 * 20);
System.out.println(unsafe.getByte(pointer + 1));
// 如果不释放内存,运行一段时间会报错java.lang.OutOfMemoryError
// unsafe.freeMemory(pointer);
}
}