直接上代码:
package org.bruce.file.handle.experiment;
/**
* @author Bruce Yang
* 测试 java heap 允许使用的最大内存
*/
public class File2ByteArray {
public static void main(String[] args) throws Exception {
testHeapMax();
}
public static void testHeapMax() {
int KB = 1024;
int MB = KB * 1024;
byte[] bytes = null;
for(int i = 0; i < 100; ++ i) {
System.out.println(i);
bytes = new byte[MB * i];
}
}
}
控制台输出为:
0
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
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at org.bruce.file.handle.experiment.File2ByteArray.testHeapMax(File2ByteArray.java:22)
at org.bruce.file.handle.experiment.File2ByteArray.main(File2ByteArray.java:11)