程老师原文地址:http://flychao88.iteye.com/blog/2188489
原文如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package
com.stevex.app.nio;
import
java.nio.ByteBuffer;
import
java.util.concurrent.TimeUnit;
public
class
DirectByteBufferTest {
public
static
void
main(String[] args)
throws
InterruptedException{
//分配128MB直接内存
ByteBuffer bb = ByteBuffer.allocateDirect(
1024
*
1024
*
128
);
TimeUnit.SECONDS.sleep(
10
);
System.out.println(
"ok"
);
}
}
|
1
2
3
4
5
|
Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory
at java.nio.Bits.reserveMemory(Bits.java:658)
at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:306)
at com.stevex.app.nio.DirectByteBufferTest.main(DirectByteBufferTest.java:8)
|
1
|
|
1
2
3
4
5
|
Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory
at java.nio.Bits.reserveMemory(Bits.java:658)
at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:306)
at com.stevex.app.nio.DirectByteBufferTest.main(DirectByteBufferTest.java:8)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package
com.stevex.app.nio;
import
java.nio.ByteBuffer;
import
java.util.concurrent.TimeUnit;
import
sun.nio.ch.DirectBuffer;
public
class
DirectByteBufferTest {
public
static
void
main(String[] args)
throws
InterruptedException{
//分配512MB直接缓存
ByteBuffer bb = ByteBuffer.allocateDirect(
1024
*
1024
*
512
);
TimeUnit.SECONDS.sleep(
10
);
//清除直接缓存
((DirectBuffer)bb).cleaner().clean();
TimeUnit.SECONDS.sleep(
10
);
System.out.println(
"ok"
);
}
}
|
注意点2:
如果你要使用direct buffer,一定不要加上DisableExplicitGC这个参数,因为这个参数会把你的System.gc()视作空语句,最后很容易导致OOM。(为啥呢?因为见下图,源码里是有
System.gc(),禁止了就不能回收,容易触发溢出
)
![java学习-【转】NIO DirectByteBuffer 内存泄露的测试 - bohu83 - bohu83的博客 java学习-【转】NIO DirectByteBuffer 内存泄露的测试 - bohu83 - bohu83的博客](http://img1.ph.126.net/V5AG4cn1qSa4tbf9mHoyfw==/6598073620833134155.png)