Based on the difference between stack and heap in java, this article introduces the garbage collection mechanism in java.

Source: Internet
Author: User

#. There are two types of memory in java. Stack and heap respectively ).

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

Heap is the storage object of the Java Virtual Machine. It is a huge memory. When you create an object, the Java Virtual Machine puts the object into the heap, and puts the address of the created object into the stack.

Therefore, the reference of the basic type and object is stored in the stack, and the object is stored in the heap.

#. Garbage collection mechanism in java

When you create a new object, java allocates the necessary memory. When you use up an object, the java Garbage Collector recycles the memory for you.

Garbage collection runs in the background in the form of a thread, searches for objects without reference, destroys the objects, and recovers the memory.

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

Then, all objects involved in the thread are marked as recently used. When all objects involved are marked, the remaining objects that are not marked are discarded.

To help virtual machines, it is a good practice to remove unnecessary objects by setting the reference to null.

Eg:

Text t = new Test ();

T. someAction ();

// All done

T = null;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.