This is an interview question that a friend encountered during an interview. When will the OutOfMemery exception be thrown? At first glance, it seems to be quite simple, but in fact, it is about the understanding of the entire JVM, and this question can be found on the Internet some random answers, in fact, basically four scenarios can be summarized.
Heap overflow
Heap overflow is common, as most of us can probably imagine. Heap memory is used to store object instances, and as long as we keep creating objects and ensure that GC Roots have a reachable path between objects to avoid garbage collection, this exception can occur very quickly after the maximum heap size limit is exceeded.
Write a code to test this by setting the heap size to 2M.
public class HeapOOM {
public static void main(String[] args) {
List<HeapOOM> list = new ArrayList<>();
while (true) {
list.add(newHeapOOM()); }}}Copy the code
The Java Heap space is running out of memory.
General way of screen can be set by – XX: + HeapDumpOnOutOfMemoryError dump out when an exception occurs in the current Memory dump snapshot to analysis, analysis can be used the Eclipse Memory Analyzer (MAT) to analyze, individual files can be downloaded in the website.
In addition, if you are using IDEA, you can use the commercial version of JProfiler or the open source version of JVM-Profiler, and IDEA2018 has built-in analysis tools, including Flame Graph and Call Tree.
Flame figure
Method area (run-time constant pool) and meta-space overflow
Method area and heap, is a thread Shared areas, include the Class file information, runtime constant pool, the constant pool, pool runtime constants and constant pool is the main difference between dynamic, namely it doesn’t have to be in the Class file content in the constant pool can enter into the runtime constant pool, runtime can also can be new constants in the pool, Like the intern() method of String.
Intern (), and we set -xx :MetaspaceSize=50m -xx :MaxMetaspaceSize=50m. Since I am using JDK 1.8, the method area existed in PermGen before 1.8. After 1.8, the concept of PermGen was abolished and Metaspace was converted. If it is the previous version, PermSize MaxPermSize can be set to the size of permgeneration.
private static String str = "test";
public static void main(String[] args) {
List<String> list = new ArrayList<>();
while (true){ String str2 = str + str; str = str2; list.add(str.intern()); }}Copy the code
When you run the code, you will find an error.
Modify the configuration again, remove the meta space limit, change the heap memory size -xMS20m -XMx20m, you can see the heap memory error.
Why is that? Intern () is a native method that returns a String representing the String in the constant pool if it already contains a String equivalent to the String. Otherwise, the String contained in this String is added to the constant pool and a reference to the String is returned.
After version 1.7, the string constant pool has been moved to the heap, so it will report an overflow of heap memory. If version 1.7 is used, you will see PermGen Space reporting an error.
Direct memory overflow
Direct memory is not part of the virtual machine’s running data region and is not limited by heap memory, but is limited by the size of the machine’s memory. Common things such as using native functions in NIO to allocate out-of-heap memory directly can cause OOM problems.
The direct memory size can be specified with -xx :MaxDirectMemorySize, otherwise it defaults to the maximum Java heap size -xmx.
An obvious feature of memory overflow caused by direct memory is that you do not see significant exceptions in the Dump file. If you find that the Dump file is very small after OOM and NIO is used directly or indirectly, you may want to check if this is the cause.
Stack overflow
The stack is thread-private and has the same lifetime as the thread. Each method will create a stack frame to store the local variable table, operand stack, dynamic link, method exit and other information when executing. The process of method call is the process of stack frame loading and unloading.
In the Java Virtual Machine specification, two exceptions are defined for the virtual machine stack:
- StackOverflowError is thrown if the stack depth requested by the thread is greater than the depth allowed by the virtual machine
- An OutOfMemoryError is raised if the virtual stack can be dynamically expanded and sufficient memory cannot be allocated during the expansion
To test this, set -xss160K, where -xss represents the stack memory size for each thread
public class StackOOM {
private int length = 1;
public void stackTest() {
System.out.println("stack lenght=" + length);
length++;
stackTest();
}
public static void main(String[] args) {
StackOOM test = newStackOOM(); test.stackTest(); }}Copy the code
The test found that no matter how you set the parameters under a single thread, it was a StackOverflow exception.
Try changing the code to multi-threaded, adjust -xss2m, because the more memory allocated to each thread, the fewer threads can fit on the stack, and the more likely it is to run out of memory. On the other hand, if the memory is insufficient, you can adjust this parameter to support more threads.
public class StackOOM {
private void dontStop() {
while (true) {
}
}
public void stackLeakByThread() {
while (true) {
new Thread(() -> dontStop()).start();
}
}
public static void main(String[] args) throws Throwable {
StackOOM stackOOM = newStackOOM(); stackOOM.stackLeakByThread(); }}Copy the code
\
Python Chinese community as a decentralized global technology community, to become the world’s 200000 Python tribe as the vision, the spirit of Chinese developers currently covered each big mainstream media and collaboration platform, and ali, tencent, baidu, Microsoft, amazon and open China, CSDN industry well-known companies and established wide-ranging connection of the technical community, Have come from more than 10 countries and regions tens of thousands of registered members, members from the ministry, tsinghua university, Peking University, Beijing university of posts and telecommunications, the People’s Bank of China, the Chinese Academy of Sciences, cicc, huawei, BAT, such as Google, Microsoft, government departments, scientific research institutions, financial institutions, and well-known companies at home and abroad, nearly 200000 developers to focus on the platform.
Long press scan code to add "Python little assistant" ▼ Click to become a community member click on itCopy the code