1.堆_Heap_介绍
通过 new 关键字,创建对象都会使用堆内存
2.特点
1.它是线程共享的,堆中对象都需要考虑线程安全的问题
2.有垃圾回收机制【堆中没有被引用的对象,会被垃圾回收】
3.堆内存溢出
异常:java.lang.OutOfMemoryError: Java heap space
代码:
public static void main(String[] args) {
int i = 0;
try {
List<String> list = new ArrayList<>();
//在catch之前 list 都有效,所以在catch之前不会被垃圾回收
String a = "hello";
while (true) {
// hello, hellohello, hellohellohellohello ...
list.add(a);
// hellohellohellohello
a = a + a;
i++;
}
} catch (Throwable e) {
e.printStackTrace();
System.out.println(i);
}
}
参数:
-Xmx8m 8m堆内存
4.堆内存诊断
//代码
public static void main(String[] args) throws InterruptedException {
System.out.println("1...");
Thread.sleep(30000);
byte[] array = new byte[1024 * 1024 * 10]; // new占用了堆空间 10 Mb
System.out.println("2...");
Thread.sleep(20000);
array = null;
System.gc();
System.out.println("3...");
Thread.sleep(1000000L);
}
1. jps 工具
查看当前系统中有哪些 java 进程
10656 RemoteMavenServer36
22112 Jps
26020
15896 Launcher
21160 Demo1_4 //案例的进程id
============================================
2. jmap 工具
查看堆内存占用情况【内存快照】:jmap - heap 进程id
eg:jmap -heap 21160
//程序运行到2...的内存快照如下:
Attaching to process ID 21160, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.172-b11
using thread-local object allocation.
Parallel GC with 13 thread(s)
Heap Configuration://堆内存的配置
MinHeapFreeRatio = 0
MaxHeapFreeRatio = 100
MaxHeapSize = 4271898624 (4074.0MB)//最大堆内存
NewSize = 89128960 (85.0MB)
MaxNewSize = 1423966208 (1358.0MB)//最大新生代内存
OldSize = 179306496 (171.0MB)//最大老年代内存
NewRatio = 2
SurvivorRatio = 8
MetaspaceSize = 21807104 (20.796875MB)
CompressedClassSpaceSize = 1073741824 (1024.0MB)
MaxMetaspaceSize = 17592186044415 MB
G1HeapRegionSize = 0 (0.0MB)
Heap Usage://堆内存的占用
PS Young Generation
Eden Space://新创建的对象都会占用伊甸园
capacity = 67108864 (64.0MB)//总容量
used = 19886304 (18.965057373046875MB)//占用
free = 47222560 (45.034942626953125MB)
29.632902145385742% used
From Space:
capacity = 11010048 (10.5MB)
used = 0 (0.0MB)
free = 11010048 (10.5MB)
0.0% used
To Space:
capacity = 11010048 (10.5MB)
used = 0 (0.0MB)
free = 11010048 (10.5MB)
0.0% used
PS Old Generation
capacity = 179306496 (171.0MB)
used = 0 (0.0MB)
free = 179306496 (171.0MB)
0.0% used
3168 interned Strings occupying 259800 bytes.
============================================
3. jconsole 工具
图形界面的,多功能的监测工具,可以连续监测
5.现象_垃圾回收后,内存占用仍然很高
jvisualvm 工具
:点击 堆 dump 【堆转储】 查询,查找前20个最大的对象
public class Demo1_13 {
public static void main(String[] args) throws InterruptedException {
List<Student> students = new ArrayList<>();
for (int i = 0; i < 200; i++) {
students.add(new Student());
//Student student = new Student();
}
Thread.sleep(1000000000L);
}
}
class Student {
private byte[] big = new byte[1024*1024];
}