preface

If you can actually write heap/stack overflows, you will naturally be conscious of avoiding them during development.

Cut the crap and cut to the chase.

Stack overflow

What is the heap

The Java heap is the largest part of the JVM’s memory management, shared by all threads, and the main area of the garbage collector.

Pack what

Do not store the basic type and object reference, all new out of the object itself, each object contains a corresponding class information.

Available VM Options (VM parameters)

-Xms60M -Xmx60M
Copy the code

Infinitely new it

public static void main(String[] args) {
    List<Object> list = new ArrayList<>();
    while(true) {        // New objects are created each time through the loop (valid scope only within the loop), and the last reference variable is lost (garbage collection will collect it).
        list.add(new Object());
 // Add objects to list indefinitely  } } Copy the code

To run an error: the Exception in the thread “is the main” Java. Lang. OutOfMemoryError: Java heap space

Stack overflow

What is the stack

Java virtual machine stack is mainly used to store local variable tables, dynamic links, etc., mainly including heap memory and stack memory.

Pack what

Store local variables and stack frames (main).

Unlimited use of it

public static void main(String[] args) {
    method();
}

public static void method(a){
 // stack overflow exception (method recursive, do not let it out of the stack)  method(); } Copy the code

To run an error: the Exception in the thread “is the main” Java. Lang. StackOverflowError

The last

The writer’s ability is limited, if there is something wrong can be communicated in the comments section.

If this article is helpful, go to 👍.

Share technology, hold on, we can win 💪!