背景知识
在JDK 1.4中新加入了NIO(New Input/Output)类,引入了一种基于通道(Channel)与缓冲区(Buffer)的I/O方式,它可以使用Native函数库直接分配堆外内存,然后通过一个存储在Java堆里面的DirectByteBuffer对象作为这块内存的引用进行操作。这样能在一些场景中显著提高性能,因为避免了在Java堆和Native堆中来回复制数据。 显然,本机直接内存的分配不会受到Java堆大小的限制,但是,既然是内存,则肯定还是会受到本机总内存(包括RAM及SWAP区或者分页文件)的大小及处理器寻址空间的限制。服务器管理员配置虚拟机参数时,一般会根据实际内存设置-Xmx等参数信息,但经常会忽略掉直接内存,使得各个内存区域的总和大于物理内存限制(包括物理上的和操作系统级的限制),从而导致动态扩展时出现OutOfMemoryError异常。 上面这段话引用自该文章
代码实验
注意到上面这段话中的黑体字:这样能在一些场景中显著提高性能,因为避免了在Java堆和Native堆中来回复制数据,然而这个“一些场景”具体指什么呢?我们通过代码做个实验看看。
1
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 1package com.winwill.jvm;
2
3import org.junit.Test;
4
5import java.nio.ByteBuffer;
6
7/**
8 * @author qifuguang
9 * @date 15-5-26 下午8:23
10 */
11public class TestDirectMemory {
12 /**
13 * 测试DirectMemory和Heap读写速度。
14 */
15 @Test
16 public void testDirectMemoryWriteAndReadSpeed() {
17 long tsStart = System.currentTimeMillis();
18 ByteBuffer buffer = ByteBuffer.allocateDirect(400);
19 for (int i = 0; i < 100000; i++) {
20 for (int j = 0; j < 100; j++) {
21 buffer.putInt(j);
22 }
23 buffer.flip();
24 for (byte j = 0; j < 100; j++) {
25 buffer.getInt();
26 }
27 buffer.clear();
28 }
29 System.out.println("DirectMemory读写耗用: " + (System.currentTimeMillis() - tsStart) + " ms");
30 tsStart = System.currentTimeMillis();
31 buffer = ByteBuffer.allocate(400);
32 for (int i = 0; i < 100000; i++) {
33 for (int j = 0; j < 100; j++) {
34 buffer.putInt(j);
35 }
36 buffer.flip();
37 for (byte j = 0; j < 100; j++) {
38 buffer.getInt();
39 }
40 buffer.clear();
41 }
42 System.out.println("Heap读写耗用: " + (System.currentTimeMillis() - tsStart) + " ms");
43 }
44
45 /**
46 * 测试DirectMemory和Heap内存申请速度。
47 */
48 @Test
49 public void testDirectMemoryAllocate() {
50 long tsStart = System.currentTimeMillis();
51 for (int i = 0; i < 100000; i++) {
52 ByteBuffer buffer = ByteBuffer.allocateDirect(400);
53
54 }
55 System.out.println("DirectMemory申请内存耗用: " + (System.currentTimeMillis() - tsStart) + " ms");
56 tsStart = System.currentTimeMillis();
57 for (int i = 0; i < 100000; i++) {
58 ByteBuffer buffer = ByteBuffer.allocate(400);
59 }
60 System.out.println("Heap申请内存耗用: " + (System.currentTimeMillis() - tsStart) + " ms");
61 }
62}
63
执行这段代码,得到的结果如下:
结论
从上面的实验结果可以看出,直接内存在读和写的性能都优于堆内内存,但是内存申请速度却不如堆内内存,所以可以归纳一下: 直接内存适用于不常申请,但是需要频繁读取的场景,在需要频繁申请的场景下不应该使用直接内存(DirectMemory),而应该使用堆内内存(HeapMemory)。