Based on the difference between stack and heap in Java, the garbage collection mechanism in Java is introduced

#There are two types of memory in Java. They are called stack and heap, respectively.

Stack is the program memory space, so all basic types and object references exist in stack.

Heap is where the Java virtual machine stores objects. It is a huge memory. When you create an object, the Java virtual machine puts the object into heap and the address of the created object into stack.

Therefore, references to basic types and objects are stored in stack; Objects are stored in heap.

#Garbage collection mechanism in Java

When you create a new object, Java allocates the necessary memory. When you run out of an object, the Java garbage collector reclaims memory for you.

Garbage collection runs in the background in the form of threads, looking for objects without useful references, destroying the objects and reclaiming memory.

Garbage collection is implemented between Java virtual machines. They usually have the same steps. First, the garbage collector obtains snapshots of running threads and all loaded classes,

Then, the objects involved in all threads are marked as recently used. When all possible objects are marked, the remaining unmarked objects are discarded.

To help the virtual machine, it is a good practice for us to actively remove some objects that are no longer needed, which can be achieved by setting the reference to null.

eg:

Text t = new test();

t.someAction();

//all done

t = null;

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>