About memory overflow

memory overflow

I was just taking a shower when Ant Financial called for a phone interview. I said to the person on the phone, "I'm taking a shower, can I call back later?"

The interview period was really awkward, because I didn't prepare well for the interview this winter vacation. One of the questions mentioned on the phone: Is there any way to make the Java program memory overflow.

Emmmmmmm...

To be fair, I have never thought about this kind of problem before. I read a book before, which talked about how to create a memory overflow. At that time, I thought that the hardware development is so fast, how can there be a memory overflow? So just turn the page.

OK, I'm going to take a good look at memory overflows.

StackOverFlow

The so-called StackOverFlow is a stack overflow, which is most likely to be thrown in scenarios where method nesting is used. So it is also very easy to understand where this Stack refers to.

Because after each thread is created, the JVM allocates the Java virtual machine stack, native method stack and pc register to the thread. Then the initialization of the method is equivalent to creating a frame in the virtual machine stack, and the invocation and return parameters of the method are equivalent to pushing and popping the stack (the initialization of local variables in the method is to allocate memory space in the frame). In this way, the infinite recursion of the method will cause the Java virtual machine stack memory overflow.

public class Test {
    public static void main(String... args) {
        Test test = new Test();
        test.hello();
        // Exception in thread "main" java.lang.StackOverflowError

    }
    
    // 递归
    public void hello() {
        hello();
    }
}

OutOfMemoryError

OutOfMemory means out of memory. This exception can be easily thrown by adding -Xmx5m to the JVM startup item. In the JVM, -Xmx5m refers to setting the maximum memory space of the Java heap to 4MB when the JVM virtual machine is running. There are also some commonly used parameters such as -Xss (single thread The size of the virtual machine stack space) -Xms (the minimum memory space of the Java heap when the JVM virtual machine is running) -Xmn (set the young generation size).


// JVM启动参数添加-Xmx5m
public class Test {
    public static void main(String... args) {
        
        // 用于存放实例化的对象,不然会被CG机制清理掉
        LinkedList<Test> list = new LinkedList<>();
        
        while(true) {
            list.add(new Test());
            //java.lang.OutOfMemoryError: Java heap space

        }
        
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325003548&siteId=291194637