Working Mechanism of java Garbage Collector

Source: Internet
Author: User
Bruce Eckel's first two chapters of Thinking in java have repeatedly stressed this point: memory leak in C ++ won't happen in java, developers do not need to consider this issue at all, which greatly reduces the development time. This is because java has a garbage collector that monitors all objects created with new, identifies objects that will not be referenced, and then releases the memory space of these objects, to be used by other new objects. But how does java's garbage collector identify it? Bruce didn't explain it. Next we will make an in-depth exploration on this point. First, we need to explain how to allocate memory for objects in java. In java, everything is an Object and a super-class Object is shared. Although everything is regarded as an object, the operated identifier is actually a "Reference" of the object ". Like String s = new String ("hello"); we get s as a reference, and then we initialize it. The reference can exist independently, just as the remote control can exist independently on the TV, but you cannot send messages to it. Otherwise, a common runtime error NullPointerException will be returned. Objects created using the new operator in java are all allocated to the heap. The Heap here is different from the heap in the data structure. The allocation method is similar to the linked list. The benefit of heap is that the compiler does not need to know how long the stored data remains in the heap, but the exact lifecycle of all items in the stack must be known. C ++ focuses on efficiency. In order to achieve the maximum execution speed, the storage space and lifecycle of objects can be determined during programming, this can be achieved by placing the object in the stack and static storage areas. However, if it is in the heap, it is dynamic and may take a lot of time to find and allocate in the heap. However, java believes that objects tend to become complex, so the overhead of searching and releasing buckets will not have a big impact on Object creation. Therefore, java uses dynamic allocation. However, there is a special case, that is, the basic type. Because according to the above description. Obviously, creating a small and simple variable with new in the heap is often not very effective. Therefore, java of these basic types adopts the same method as c ++ and stores them in the stack. But in order to store them in the heap, and to store basic data types in the container (all objects in the container are referenced, but objects in the stack are not referenced ), java also provides the package class for the basic type, which may solve many students' doubts about the package class. Java heap is more like a conveyor belt. Every time a new object is assigned, it moves one cell forward. This means that the object storage space is allocated quite quickly. Java's "heap pointer" is simply moved to an unallocated field. That is to say, when allocating space, the "heap pointer" only moves forward in sequence, regardless of whether or not the subsequent objects are to be released. If the program exits before the available memory is exhausted, the garbage collector will not be activated. However, since the "heap Pointer" only moves forward sequentially, one day the memory will be exhausted and the garbage collector will start to release the memory. How can we determine whether an object should be recycled? The answer is that when the stack or static storage area does not reference this object, it indicates that the Program (member) is not interested in this object, and it should be recycled. There are two ways to know whether the object has been referenced: first, to retrieve the reference of the object on the traversal stack, and second, to retrieve the object by traversing the reference of the stack or static storage area. The implementation of the former is called the reference counting method, which means that when a reference is connected to an object, the reference count is incremented by 1. When the reference leaves the scope or is set to null, the reference count is reduced by 1, this method has a defect. If there is a circular reference between objects, there may be a situation where "the object should be recycled, but the reference count is not zero. Java uses the latter. In this way, the Java virtual machine uses an adaptive garbage collection technology to process the found surviving objects (that is, not garbage ), java has two methods: 1. stop-and-copy: stop the program and then copy all the surviving objects from the current heap to another heap, all the items that are not copied are junk. When objects are copied to the new heap, they are compact. Low Efficiency: first, two heaps occupy 200% of space. Second, copying a large number of living objects is a great waste if there is less garbage. 2. mark-and-sweep: traverses all references from the battle and static storage areas to find all the surviving objects. If the objects are alive, mark them. The cleanup action starts only when all the tags are marked. During cleaning, unlabeled objects will be released without any skin action. However, the remaining space is not consecutive. If the garbage collector wants to get continuous space, it has to reorganize the remaining objects. [Note] "stop-Copy" and "mark-clean" are nothing more than "find clean items in a large amount of garbage and find garbage in a large number of clean items ". Different Environments use different methods to improve efficiency. "Stop-Copy" means that this garbage collection action is not performed in the background; on the contrary, when the garbage collection action occurs, the program will be paused. Some people regard garbage collection as a background process with a low priority. In fact, this is not the case. When the number of available memory is lower, the Sun version of Garbage Collector will suspend the running of the program. Similarly, the "mark-sweep" operation must be performed only when the program is suspended. [Note] in Java virtual machines, memory allocation is measured in large blocks. Each block uses the corresponding algebra (generation count) to record whether it is still alive. Algebra increases with the number of references. The garbage collector sorts the newly allocated blocks after the last recycle action. This is helpful for handling a large number of short-lived temporary objects. The garbage collector regularly performs complete cleanup operations-large objects are still not copied (only increase in algebra), and those blocks of small objects are copied and organized. The Java virtual machine monitors all objects. If all objects are stable and the efficiency of the garbage collector is reduced, switch to the "mark-sweep" method. Similarly, the Java Virtual Machine tracks the effect of "mark-sweep". If many fragments occur in the heap space, it switches to the "stop-Copy" mode. This is the "Adaptive" technology. Therefore, the Java garbage collector is an adaptive, generational, stop-copy, Mark-Clean garbage collector. [Note] most of the articles are excerpted from the Internet, and the addresses are scattered. The authors also refer to the description of thinking in java for multiple times. The summary is very inadequate. If you have a high opinion, I hope you will be enlightened.

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.