Let's take a look at the JVM Memory Model:
In general, the JVM memory model is divided into two major parts:
Permanent space and heap space ).
The stack memory (stack space) is generally not in the JVM memory model, because the stack memory belongs to the Thread level.
Each thread has an independent stack memory space.
Permanent space stores loaded class-level objects such as class, method, field, and so on.
Heap space mainly stores object instances and arrays.
Heap space is composed of old generation and new generation. Old Generation stores instance objects with a long life cycle, while new object instances are generally placed in new generation.
New generation can be further divided into the Eden area (the garden of eden in the Bible) and the survivor area. New object instances are always placed in the Eden area first, and the survivor area serves as the buffer for the Eden and old areas, you can transfer an active object instance to the old zone.
Is the activity diagram of the process in which JVM applies for a new object in the memory space (heap space) (Click to see the big picture ):
Yes, our common out of memory overflow exception is caused by insufficient heap memory space to store new object instances.
Memory overflow in the permanent zone is rare. It is generally caused by the need to load a large amount of class data, which exceeds the non-heap memory capacity. This usually occurs when a web application is started. Therefore, we recommend that you use the pre-load mechanism to locate and solve the problem during deployment.
Stack memory also overflows, but it is rare.
Heap Memory Optimization:
Adjust the JVM startup parameters-XMS-xmx-XX: newsize-XX: maxnewsize, such as adjusting the initial heap memory and the maximum memory-xms256m-xmx512m. Or adjust the initial memory and maximum memory of the New Generation-XX: newsize = 128 M-XX: maxnewsize = 128 M.
Permanent zone memory optimization:
Adjust the permsize parameter, for example,-XX: permsize = 256 m-XX: maxpermsize = 512 M.
Stack memory optimization:
Adjust the stack memory capacity of each thread, such as-xss2048k
In the end, the memory occupied by a running JVM = heap memory + permanent zone memory + total stack memory occupied by all threads.