Simulate a memory overflow situation
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* 向List集合中添加100万个字符串,每个字符串由1000个UUID组成。如果程 序能够正常执行,最后打印ok。
*/
public class TestJvmOutOfMemory {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
for (int i = 0; i < 10000000; i++) {
String str = "";
for (int j = 0; j < 1000; j++) {
str += UUID.randomUUID().toString();
}
list.add(str);
}
System.out.println("ok");
}
}
-Xms8m -Xmx8m -XX:+HeapDumpOnOutOfMemoryError
Analysis with MAT
It can be seen from the analysis results that 92.16% of the memory is occupied by Object[], so it is suspicious.
An overview of the main functions of the MAT interface
Generate heap dump in real time
Histogram
The bar chart shows the usage of each class, such as the number of classes, the space occupied, etc.
grouping
sort
Regular search
View citations
code
import java.util.ArrayList;
import java.util.Random;
/**
* -Xms30m -Xmx30m -XX:SurvivorRatio=8 -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/opt/dump.hprof
*/
public class OOMTest {
public static void main(String[] args) throws InterruptedException {
ArrayList<Box> list = new ArrayList<>();
while(true){
Thread.sleep(100);
list.add(new Box(new Random().nextInt(1024 * 1024)));
}
}
}
class Box{
private byte[] data;
public Box(int length) {
this.data = new byte[length];
}
}
Comparing two histograms
In and out references
domination tree
Display thread information
Display heap overall information
Display overall heap information, such as some objects that consume the most.