English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JVM divides the memory space into two parts: one is the stack, and the other is the heap space. The stack space is mainly used to store the order of method execution and local variables.
The stack always stores blocks in LIFO order, while heap memory uses dynamic allocation to allocate and deallocate memory blocks.
The memory allocated to the heap will exist until one of the following events occurs:
Program termination
Amnesia
On the contrary, the memory allocated to the stack always exists until the function returns. Here are the differences.
Serial number | Key | Stack | Heap memory |
---|---|---|---|
1 | Basic | The stack memory is used to store short-lived items, such as local variables, reference variables of objects | Heap memory is allocated for storing objects and JRE classes. |
2 | Order method | The stack always retains in LIFO (Last In First Out) order | Heap memory is dynamically allocated, and there is no fixed pattern for allocating and deallocating blocks in memory |
3 | Size | We can use JVM parameters-XSS to increase the size of the stack memory | We can use JVM options-Xms and-Use Xmx to increase or decrease the size of the heap memory. |
4 | Visibility | Variables are only visible to the owner thread | All threads are visible |
5 | Exception | JVM will throw java.lang.StackOverflowError | JVM will throw java.lang.OutOfMemoryError |