How the garbage collector works in Java programming ideas

Source: Internet
Author: User
Tags comparable

I have been busy for a few days, so I have nothing to do with learning. I started reading books later. I think I still have 10 books. Oh. This winter vacation is very difficult.

The following content is excerpted from Java programming thoughts and further sorted out

In the Previously Used programming languages, it is very expensive to allocate objects on the stack. Therefore, readers will naturally feel that all objects in Java(Except for basic types)The allocation method is also very high. However,The garbage collector significantly improves the object creation speed.It sounds strange-the release of a bucket actually affects the allocation of the bucket, but this is indeed the way some java virtual machines work. This also means that the speed at which Java allocates space from the heap is comparable to that of other languages.

For example, you can think of a heap in C ++ as a yard where every object is responsible for managing its own territory. After a period of time, the object may be destroyed, but the site must be reused. In some java virtual machines, the implementation of the heap is completely different: it is more like a conveyor belt. Every time a new object is allocated, it moves one cell forward.

This means that the object storage space is allocated very quickly. Java's "heap pointer" is simply moved to an unallocated area, which is more efficient than the space allocated by C ++ on the stack. Of course, there are a small amount of additional expenses in the bookkeeping work in the actual process, but it is not as overhead as it is to find the available space.

You may have realized that the heap in Java may not work exactly like a conveyor belt. If that is the case, frequent page scheduling will inevitably occur-Move it out of the hard disk, so it seems that you need more memory than you actually need. Page scheduling will significantly affect the performance. In the end, after creating enough objects, the memory resources will be exhausted. The secret lies in the intervention of the garbage collector.

When it works, it recycles space while compress objects in the heap so that the "heap Pointer" can easily move closer to the start of the conveyor belt, avoid page errors as much as possible. Through the Garbage Collector to rearrange objects, a high-speed heap model with infinite space available for allocation is realized.

To better understand garbage collection in Java, it is helpful to first understand the garbage collection mechanism in other systems.

I. Reference count

Reference counting is a simple but slow garbage collection technology. Each object contains a reference counter. When there is a reference link to an object, the reference counter is added to 1.

Although the overhead of managing reference records is not largeThe entire life cycle of the program will continue to occur.The garbage collector traverses the list containing all objects. When the reference count of an object is 0, the space occupied by the object is released (however, in reference mode, objects are often released immediately when the value is changed to 0 ). This method hasDefect. 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.For the Garbage Collector, it takes a lot of effort to locate such an interactive self-referenced object group. Reference records are often used to describe how garbage collection works, but it seems thatIt has never been applied to any Java Virtual Machine implementation.

Ii. "trace reference"
In some faster modes, the garbage collector is not based on the reference count technology. They rely on the idea that any "active" object will be traced back to its survivalReferences in a stack or static storage area.This reference chain may pass through several object layers.

Therefore, if you traverse all references from the stack and static storage areas, you can find all "active" objects.For each detected reference, you must trace the object it references, and then all references contained in the object, until all the networks formed by "References rooted in stacks and static storage zones" are accessed.All objects you have accessed must be "active. Note:Solved the problem of "interactive self-referenced object group"-this phenomenon will not be found at all, so it will be automatically recycled.

3. Stop-and-copy)
In this way, the Java Virtual Machine will adopt an adaptive garbage collection technology. As for how to deal with the found surviving objects, it depends on the implementation of different Java virtual machines. One method is calledStop-and-copy ).Obviously, this means that the program is paused first (so itNot in background recycle Mode), And then all the surviving objectsCopying data from the current heap to another heap is junk. (Pick-up job)When objects are copied to the new heap, they are one by one, so the new heap keeps in a compact arrangement, and then the new space can be allocated simply and directly using the aforementioned method.

When moving an object from one place to another, all references pointing to it must be corrected. References in heap or static storage can be directly corrected, but there may be other references pointing to these objects, which can be found during traversal (as you can imagine, there is a table, map the old address to the new address ).

For this so-called "replication recycler,Lower efficiencyThere are two reasons for this.

First, you have to have two heaps, and then you haveTwo Separated heapsTo maintain more than twice the actual space. Some Java virtual machines can handle this problem by allocating resources from the heap as needed.BlocksLarge Memory, replication occurs between these large memory blocks.

The second problem is thatCopy. After the program enters a stable state, only a small amount of garbage may be generated, or even no garbage.

4. Mark-and-sweep)

Even so, the replication recycler still copies all memory from one place to another, which is a waste. To avoid this situation, some java virtual machines will check: If there is no new garbage, it will be converted to another working mode (that is"Adaptive"). This model is called Mark-and-sweep, which was used by earlier versions of Sun's Java virtual machine. For general purposes, the "mark-sweep" method is quite slow, but when you know that only a small amount of garbage is generated or even no garbage is generated, it is very fast.

The idea behind "mark-sweep" is also to traverse all references from the stack and static storage areas to find all the surviving objects. Every time it finds a surviving object, it will set a tag for the object, and no object will be recycled in this process. The cleanup operation starts only when all tasks are marked. During the cleaning process, unlabeled objects will be released without any replication action. Therefore, the remaining heap space is not consecutive. If the garbage collector wants to get continuous space, it has to reorganize the remaining objects.

"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. According to Sun's documents, many references regard garbage collection as a background process with a low priority, but in fact, the garbage collector was not implemented in earlier versions of Java virtual machines in Sun. When the number of available memory is low, the sun version of the garbage collector will pause running the program. Similarly,The marking-cleaning operation must also be performed when the program is suspended.

5. "Block"

As mentioned above, in the Java Virtual Machine discussed here, the memory allocation is largeBlock"Is the unit. If the object is large, it occupies separate blocks. Strictly speaking, "stop-Copy" requires that all surviving objects be copied from the old heap to the new heap before the old objects are released, which leads to a large amount of memory replication. With blocks, the garbage collector can copy objects to the discarded blocks during collection. Each block uses the corresponding algebra (generation count) to record whether it is still alive.

Generally, if a block is referenced somewhere, its algebra will increase; the Garbage Collector will sort out the newly allocated blocks after the last collection 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 (their algebra is increased), and blocks containing small objects are copied and organized.

The Java virtual machine monitors,If all objects are stable and the efficiency of the garbage collector is reduced, switch to the "mark-clean" method.Similarly, the Java Virtual Machine tracks the effect of "mark-sweep,If there are many fragments in the heap space, the "stop-Copy" method will be switched back. This is the "Adaptive" technology,You can give it an adaptive, generational, stop-copy, Mark-Clean garbage collector.

Java virtual machines have many additional technologies to speed up. EspeciallyLoaderOperations are called"Instant" (just-in-time, JIT)Compiler Technology. This technology can translate all or part of the programLocal machine code(This isJava Virtual MachineTo improve the program running speed. When you need to load a class (usually when creating the first object for the class), the compiler first finds its. Class file and then loads the byte code of the class into the memory.

At this time, there are two solutions to choose from. One is to let the real-time compiler compile all the code. However, this approach has two drawbacks:The loading actions are dispersed throughout the life cycle of the program.It takes more time to accumulate the code, and the length of the executable code is increased (the bytecode is much smaller than the local machine code after the instant compiler expands), which leads to page scheduling, this reduces the program speed.

Another approach isLazy cvaluation)This means that the instant compiler only compiles the code when necessary. In this way, code that will never be executed may not be compiled by JIT at all. JavaHotspotThe technology uses a similar method, and the code is optimized every time it is executed.The higher the number of executions, the faster the execution speed.

Summary:

1. The release of a bucket affects the distribution of the bucket.

2. the speed at which Java allocates space from the stack is comparable to that of other languages.

3. The reference count may be "the object should be recycled, but the reference count is not zero.

4. Stop-copy: Pause the program and copy it from the current heap to another heap.

5. "Stop-Copy" and "mark-clean" are not in background recycle mode.

6. "Adaptive" technology is used to switch from "stop-Copy" to "mark-clean ".

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.