There are some knowledge of memory management and garbage collection that has been occurring throughout the tutorial. Here's a little summary.
Java is run in the memory environment that the JVM is virtual. Memory is divided into stacks (stack) and heap (heap) two parts. We will examine the two areas separately.
Stack
The basic concept of stacks: stacks (stack). Many languages use stack data structures to record the order of function calls and related variables (refer to Linux from program to process).
In Java, the stacks in the JVM record the thread's method calls. Each thread has a stack. In the course of a thread's operation, if there is a new method call, then the corresponding stack of the thread will add a storage unit, that is, frame (frame). In a frame, the parameters, local variables, and return addresses of the method call are saved.
Call stack
Java parameters and local variables can only be variables of a basic type (such as int), or a reference to an object (reference). Therefore, in the stack, only variables and object references with basic types are saved.
The object that the reference points to is saved in the heap. (reference may be a null value, that is, not point to any object)
References and objects
When the invoked method ends, the corresponding frame of the method is deleted, and the space occupied by the parameter and the local variable is released. The thread goes back to the original method and continues execution. When all the stacks are empty, the program also ends.
Heap
As mentioned above, stacks (stack) can take care of themselves. But the heap must be treated with care. A heap is an area of the JVM that is freely assigned to an object. When we talk about garbage collection (garbage collection), we mainly recycle the space of the heap (heap).
Java's normal objects live in the heap. Unlike stacks, the heap space is not emptied as the method call ends. Therefore, an object created in a method can continue to exist in the heap after the method call has ended. The problem with this is that if we constantly create new objects, the memory space will eventually be depleted.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/