Analysis of Java garbage collection mechanism

Source: Internet
Author: User
Keywords: Java Learning

Note:TheArticleFor reprinting!

We know that manyProgramAll the design languages allow dynamic allocation of memory space during the runtime. Memory Allocation varies depending on the syntax structure of the language. However, no matter which language is used for memory allocation, the initial address of the allocated memory block is returned, that is, a pointer to the first address of the memory block.

When the allocated memory space is no longer needed, in other words, when the handle pointing to the memory block exceeds the usage range, the program or its runtime environment should reclaim the memory space, to save valuable memory resources.

 

In C, C ++, or other programming languages, both the object and dynamically configured resources or memory must be declared by the programmer and recycled, otherwise, the resources will be consumed, resulting in a waste of resources or even a crash. However, manual memory recovery is often a complex and arduous task. It is very difficult to determine whether the occupied memory space should be recycled! If a program cannot recycle its memory space and the system does not have any memory space to allocate when the program runs, the program will crash. Generally, the memory space that we can't recycle After allocating is called "Memory leakage (memory leaks )".

The potential danger of the above program design is not allowed in a rigorous and secure language such as Java. However, the Java language neither limits the flexibility of programmers to write programs nor removes part of declared objects (otherwise it is not an object-oriented programming language ), the best solution is to start with the features of the Java programming language. Java provides a system-level thread, namely, the garbage collection thread, to track the memory space allocated by each block, when the Java Virtual Machine (Java Virtual Machine) is in an idle loop, the garbage collector thread will automatically check the memory space allocated for each fast distribution, then, it automatically recycles useless memory blocks that can be recycled quickly.

 

The garbage collector thread is a low-priority thread. in the life cycle of a Java program, it only has the opportunity to run when the memory is idle. It effectively prevents Memory leakage and greatly saves valuable memory resources. However, there are a variety of methods to execute the Garbage Collector through the Java Virtual Machine.

The following describes the features of the garbage collector and its execution mechanism:

The Zookeeper collector system has its own solution to determine which memory block should be recycled and which does not meet the requirements. The execution of the garbage collector in a Java program is automatic and cannot be enforced. Even if the programmer can clearly determine that a piece of memory is useless, it should be recycled, programmers cannot force the Garbage Collector to recycle the memory block. The only thing a programmer can do is to call the system. GC method to "recommend" the execution of the garbage collector, but it is unknown when it can be executed. This is also the main drawback of the garbage collector. Of course, compared to the great convenience it brings to programmers, this disadvantage is not concealed.

The main features of the garbage collector are:

1. The goal of the garbage collector is to recycle the memory space of useless objects, so as to avoid Memory leakage, save memory resources, and avoid programsCode.

2. the garbage collector determines whether an object's memory space is useless. If the object cannot be referenced by any "active part" in the program, let's say, the memory space of this object is useless. The so-called "activity part" refers to a part of the program that participates in the call of the program. It is being executed and has not been completed yet.

3. Although the Garbage Collector thread runs as a low-priority thread, when the amount of available memory in the system is too low, it may suddenly execute to save memory resources. Of course, the execution is unpredictable.

4. The Garbage Collector cannot be executed forcibly, but the programmer can call the system. GC method to recommend the execution of the garbage collector.

5. There is no guarantee that a useless object will be collected by the garbage collector, or that the garbage collector will be executed in a Java code segment. Because the memory space allocated during program execution may be retained until the execution of the program is completed, unless the space is reassigned or recycled by other methods. It can be seen that it is impossible to completely eliminate the memory leakage. But do not forget that Java's garbage collector frees programmers from the heavy work of manual memory space collection. Suppose a programmer needs to use C or C ++ to write code for a 0.1 million-line statement, so he will fully understand the advantages of Java's garbage collector!

6. There is also no way to predict which object will be first collected in a group of objects that comply with the collection criteria of the garbage collector.

7. The circular reference object will not affect its collection by the garbage collector.

8. You can use the reference variables (handle handles) of an object to initialize to a null value to indicate that the Garbage Collector collects the object. However, if the object is connected to an event listener (a typical AWT component), it cannot be collected. Therefore, before setting a reference variable to a null value, you should pay attention to whether the object pointed to by the reference variable is monitored. If yes, you must first remove the listener before assigning a null value.

9. Each object has a finalize () method, which is inherited from the object class.

10. The finalize () method is used to recycle system resources other than memory, such as file processors and network connectors. The call sequence of the method is irrelevant to the creation sequence of the objects used to call the method. In other words, when writing a program, the order of the method and the actual call order of the method are irrelevant. Note that this is only a feature of the finalize () method.

11. Each object can only call the finalize () method once. If an exception occurs during execution of the finalize () method, the object can still be collected by the garbage collector.

12. The garbage collector tracks every object, collects inaccessible objects (that is, the object is not called by any "active part" of the Program), and recycles the memory space it occupies. However, during garbage collection, the garbage collector calls the finalize () method to let other objects know its existence, the "recovery" of inaccessible objects is reachable. Since each object can only call the finalize () method once, each object can only "Recover" once.

13. The finalize () method can be called explicitly, but it cannot be used for garbage collection.

14. The finalize () method can be overloaded, but only methods that have the characteristics of the initial finalize () method can be called by the garbage collector.

15. The finalize () method of the subclass can call the finalize () method of the parent class explicitly as the last appropriate operation of the subclass object. However, the Java compiler does not regard this as an overriding operation, so it does not check its calls.

16. When the finalize () method has not been called, The system. runfinalization () method can be used to call the finalize () method to achieve the same effect and collect unwanted objects.

17. when the execution of a method is complete, the local variables in the method will be out of the scope of use, which can be used as garbage collection, but when the method is called again in the future, the local variables are re-created.

18. The Java language uses a "flag swap area for garbage collectionAlgorithm". This algorithm traverses the handles of each object in the program, marks the referenced object, and then recycles the objects that have not been marked. The so-called traversal can be simply understood as "checking each ".

19. The Java language allows programmers to add the finalize () method for any method, which will be called before the Garbage Collector exchanges recycle objects. However, do not rely too much on this method to recycle and reuse system resources, because the execution result after this method is called is unpredictable.

Through the above understanding of the characteristics of the garbage collector, you should be able to clearly define the role of the garbage collector, and the garbage collector to determine whether a piece of memory space is useless standards. Simply put, when you assign a null value to an object and redirect the object to its reference, the object meets the collection criteria of the garbage collector.

Determining whether an object meets the collection standards of the garbage collector is an important test site (this is the only test site) of the garbage collector in the sun programmer certification test ). Therefore, in a given piece of code, the examinee should be able to determine which object meets the criteria collected by the garbage collector and which does not. The following describes the question types that may appear in the certification exams:

Object OBJ = new object ();

We know that obj is a handle of the object. When the new keyword is displayed, the memory space is allocated to the new object, and the OBJ value is the first address of the newly allocated memory space, that is, the value of the object (please note that, the object Value and the object content have two different meanings: the object Value refers to the first address of its memory block, that is, the object handle; the object content is its specific memory block ). If OBJ = NULL exists, the memory block pointed to by obj is useless because the variable is not called below.

Take a look at the following questions that may occur during the certification exams:

Procedure 1:

1. fobj = new object ();

2. fobj. Method ();

3. fobj = new object ();

4. fobj. Method ();

Q: In this code, which lines of fobj comply with the collection standards of the garbage collector?

Answer: Row 3. Because the fobj in row 3rd is assigned a new value, a new object is generated, that is, a new memory space is replaced, which is equivalent to a null value for fobj in row 1st. This type of question is the easiest in the certification 0 exam.

Procedure 2:

1. Object sobj = new object ();

2. Object sobj = NULL;

3. Object sobj = new object ();

4. sobj = new object ();

Q: In this code, the first line of memory space meets the collection standard of the garbage collector?

Answer: rows 1st and 3rd. Because the sobj value for the 2nd behavior is null, The sobj value for this 1st row complies with the collection standard of the garbage collector. The value of row 4th is equivalent to NULL for sobj, so the sobj of row 3rd also complies with the collection standard of the garbage collector.

If there is an object handle a, and you use a as a parameter of a constructor (A), even if you assign a value of null to, A does not comply with the collection standards of the garbage collector. It is not until the new object constructed by the constructor above is assigned a null value that a can be collected by the garbage collector.

Section 3:

1. Object aobj = new object ();

2. Object bobj = new object ();

3. Object cobj = new object ();

4. aobj = bobj;

5. aobj = cobj;

6. cobj = NULL;

7. aobj = NULL;

Q: In this code, the first line of memory space meets the collection standard of the garbage collector?

Answer: Row 3. Note that this type of question type is the most difficult question type for certification exams.

Row 1-3 creates three objects of the object class: aobj, bobj, and cobj.

Row 4: At this time, the handle of the object aobj points to bobj, so the execution of this row cannot make aobj conform to the collection standard of the garbage collector.

Row 5: At this time, the handle of the object aobj points to cobj, so the execution of this row cannot make aobj conform to the collection standard of the garbage collector.

Row 6: no object meets the collection standard of the garbage collector.

Row 7: The object cobj complies with the collection standard of the garbage collector, because the cobj handle points to a single address space. At the time of row 6th, cobj has been assigned null, but cobj also points to aobj (row 5th). Therefore, cobj does not comply with the collection standard of the garbage collector. In row 7th, the address space pointed to by aobj is also given a null value, which means that the address space pointed to by cobj has been completely given a null value. Therefore, cobj eventually meets the collection standards of the garbage collector. However, for aobj and bobj, it is still unable to determine whether it meets the collection standards.

In short, in Java, there are only two criteria for determining whether a piece of memory space meets the Garbage Collector collection standards:

1. the null value is assigned to the object, which has never been called.

2. A new value is assigned to the object, which re-allocates the memory space.

Finally, I would like to remind you that a piece of memory space meets the collection standards of the garbage collector, and does not mean that this memory space will be collected by the garbage collector.

 

 Reference:Http://xiayanhua-donghae.javaeye.com/blog/478753

 

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.