Java heap management - garbage collection
Abstract: Java heap management - garbage collection
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="279" height="86" align="center" valign="top"> </ td> <td width="405" valign="top"> 1 INTRODUCTION
The reactor is a Java run-time data, instance of the class (object) from the allocated space. Java Virtual Machine (JVM) running in a pile of stored procedures established by the application of all objects, these objects through new, newarray, anewarray and multianewarray such instructions established, they do not require explicit code to be released. Generally, the reactor is to be responsible for garbage collection, although JVM norms do not require special recycling technology, or simply does not need garbage collection, but because of the limited nature of memory, JVM in the realization of all a garbage collection managed by the reactor. Recycling is a dynamic storage management technology, it no longer automatically release the object of procedures used, in accordance with the specific algorithm for refuse collection resources to achieve automatic recovery function.
2 refuse collection significance
In C + +, object memory of the operation before the end of the procedure has been occupied in the clear before the release can not be allocated to other objects, and in Java, when not at the original object reference to a target allocation of memory, the memory will become garbage. JVM threads of a system-level memory will be automatically release of the block. Refuse collection procedures means that the object is no longer needed "useless information", the information will be discarded. When an object is no longer invoked when the memory space occupied by recycling it, in order to space the new object was later use. In addition to the release of useless objects, garbage collection can also remove debris memory record.
The object creation and garbage collection for the release of the discarded objects of memory space, the memory will appear debris. Debris object is allocated to the memory block between free memory hole. Defragmentation will be occupied by the heap memory moved to the end of the reactor, will be sorted out JVM memory allocated to the new object.
Refuse collection to automatically release memory space, reducing the burden of programming. This Java virtual machine has some advantages. First, it can increase the efficiency of programming. In the absence of garbage collection mechanism, it could take a lot of time to solve a difficult problem of memory. In the use of the Java programming language, on the garbage collection mechanism can greatly shorten the time. Second, it protects the integrity of the proceedings, garbage collection safety of the Java language is an important part of strategy.
Refuse collection of a potential shortcoming is that it costs affect performance. Java virtual machine must be useful in tracking operational procedures for the object, but eventually released useless objects. This process takes time processor. Second garbage collection algorithm is not complete, some of the earlier use of garbage collection algorithms will not be able to guarantee 100% of all waste collected memory. Of course, with the garbage collection algorithm, as well as hardware and software continue to improve the operating efficiency is on the rise, these problems can be solved.
3 refuse collection algorithm analysis
Java language specification did not clearly spelled out what JVM use garbage collection algorithm, but any general garbage collection algorithm to do two basic things: (1) useless information found objects (2) recovery was useless objects occupied memory space so that the space can be re-used.
Most of the garbage-collection algorithms used the root sets (root set) the concept of so-called Gen-set for the execution of Java programs can access the application of a collection of variables (including local variables, parameters, type variables), process variables can be used to invoke object's properties and call the method of object. Refuse collection first need to determine what started from the roots up and is not up to what is, from Gen-Set up activities are the target object, as they can not be recycled garbage, which also includes sets indirectly from the root up target. Root through arbitrary path is not set up to meet the target of the conditions of refuse collection should be recycled. Here are several commonly used algorithms.
3.1 reference count (Reference Counting Collector)
Reference count method is not only the use of root sets recycling properly, the use of the algorithm used to distinguish viable counter object and the object is no longer used. Generally, the pile every object quoted a corresponding counter. When creating an object every time and assign a variable, the home used for a counter. When objects are arbitrarily assign variables, each cited counter plus 1. When the object to the scope after (the discarded objects no longer in use), quoted by a counter once used for counter 0, on target to meet the conditions for the refuse collection.
Based on the use of the refuse collection counters running faster, not long interruption procedures, and must be suitable for real-time operating procedures. However, the procedure invoked counter implementation of the expenses, because each object assign new variables, plus a counter, and each of the existing object to the scope of Health, counters by 1.
3.2 tracing algorithm (Tracing Collector)
Tracing algorithm is used to solve the problem of counting method, in which the use of root-concept. Based on tracing algorithm for the refuse collection started from the root-scanning, which identify objects up, which can not object, and marked up in one way or another object, for example, each set up to target one or more of. In the process of scanning identification, tracing algorithm based on the refuse collection also known as the marking and clearance (mark - and-sweep) garbage collectors.
3.3 compacting algorithm (Compacting Collector)
In order to solve reactor debris, garbage collection based on tracing the absorption of the Compacting algorithm thinking, in the process of removing the algorithm will be moved to heap all the object of the side, the other side of the reactor into a neighboring free memory , it will be collected for all objects moving all cited updated so that these quoted in a new location can identify the original object. Compacting algorithm based on the realization of the collection, the general increase in handle and handle table.
3.4 coping algorithm (Coping Collector)
The algorithm is proposed in order to overcome the overhead handle and solve the garbage heap of debris recovery. It began when the reactor is divided into an object of a number of leisure and face, from the object of procedures for the allocation of space object, object when full, coping algorithm based on the refuse collection from the root object on scanning activities, and activities of each object copied to the free surface (made of the target activities of memory are not free holes), this object has become a free-surface, the original object into a free-surface, the program will face in the new object in memory allocation.
Based on a typical coping garbage collection algorithm is stop-and-copy algorithm, it would pile into objects of regional and free surface, the object of regional and free-switching process, the procedures suspended.
3.5 generation algorithm (Generational Collector)
Stop-and-copy refuse collection for a flaw is the collection of all activities must be copied object, this time for the procedure, it is inefficient for coping algorithm. In the process of the law, there is: the majority of the targets of a comparatively short time, the existence of a few relatively long time. Therefore, the generation algorithm will be divided into two or more reactor, the reactor as an object of each generation (generation). As most of the targets relatively short time, with the non-use of the procedures in disposing of the object, refuse collection for the youngest son from a pile collected objects. At behalf of the refuse collection running, the last surviving operation moved to the target of the next generation of the highest pile, as the older generation of the reactor will not always be recycled, thus saving time.
3.6 adaptive algorithm (Adaptive Collector)
Under specified circumstances, some garbage collection algorithm will be superior to other algorithms. Based on Adaptive Algorithm for refuse collection is monitoring the use of the current reactor, and select the appropriate algorithm for garbage collection.
4 Perspective Java garbage collection
Perspective 4.1 command line parameters for the operation of refuse collection
Use System.gc () JVM can be used regardless of what kind of garbage collection algorithms, can request Java's garbage collector. In a command line parameter - verbosegc can view the use of the Java heap memory, its format is as follows:
Java-verbosegc classfile
Can see examples:
Class TestGC
(
Public static void main (String [] args)
(
New TestGC ();
System.gc ();
System.runFinalization ();
)
)
In this example, a new object is created, because it does not use, it quickly becomes the object up, procedures compiler, the Executive order: java-verbosegc TestGC after the results were as follows:
[Full GC 168K-> 97K (1984K), 0.0253873 secs]
Machine environment, Windows 2000 + JDK1.3.1 arrow data before and after the 168 K and 97 K, respectively that all refuse collection GC survival after use of object memory capacity, the 168 K-97K = 71K capacity of the object being recalled, in brackets 1984 K for the data stack memory of capacity, the time required to collect is 0.0253873 seconds (the time when each implementation will be different).
Perspective 4.2 finalize method for the operation of refuse collection
Refuse collection in the JVM an object of the collection before the general requirements call procedures appropriate methods release resources, but in the absence of clear release resources, Java provides a default mechanism for the termination of the object and release resources, this method is finalize (). It is the prototype:
Protected void finalize () throws Throwable
In finalize () method returns, the object disappeared, garbage collection begun to be implemented. The prototype throws Throwable that it can be thrown out of any type of anomaly.
The reason to use finalize (), because sometimes need to be taken with the Java different from the ordinary methods for a way through the allocation of memory to do some things with the C style. This can mainly be through "natural method" to carry out, it is from Java, non-Java method calls as a way. C and C + + is currently the only method of access to natural language support. However, they can call other languages of the subroutine, has been able to effectively call anything. In the non-Java code within the C may be able to call malloc () function series, with its allocation of storage space. But unless the call free (), or storage space will not be released, resulting in memory "loophole" to happen. Of course, free () is a C and C + + function, we need to finalize () within an inherent method of calling it. In other words, we can not use excessive finalize (), it is not a common ideal for the work of the removal.
The removal work in general, in order to remove an object, that object in the hope that the user must place the call to get rid of a removal method. This C + + to "destroy" is a little inconsistent with the concept. In C + +, would undermine all objects (removal). Or in other words, all objects are "should be" destroyed. If the C + + object-creation of a local object, for example, created in the stack (in Java is impossible), then remove or destroy the work will be in the "end brackets spent" represents the creation of this object at the end of the scopes carried out. If the object is to create a new (similar to Java), then when the programmer call C + + delete orders (Java there is no such order), will accordingly call for the destruction. If programmers forget, then never call destruction, we finally will be a memory of the "loophole", and also includes other parts of the object will never be cleared.
On the contrary, Java does not allow us to create local (local) targets - in any case to use new. But in Java, there is no "delete" command to release, because garbage collectors will help us to automatically release storage space. Therefore, if the position of stand comparison to simplify, we can say that because of the garbage collection mechanism, so no damage of Java. However, with subsequent in-depth study, we will know the existence of garbage collectors can not completely eliminate the need for the destruction or the elimination of damage that can not be representative of the kind of mechanism for the needs (and can not directly call finalize ( ), it should be avoided as far as possible to use it). If we want the implementation of storage space in addition to the release of some form other than the removal work is still the need to call a method in Java. It is equivalent to the destruction of C + +, which is not easy.
Below this example to demonstrate experienced by the refuse collection process, and in front of a summary statement.
Class Chair (static boolean gcrun = false; static boolean f = false; static int created = 0; static int finalized = 0; int i; Chair () (i = + + created; if (created == 47) System.out . println ( "Created 47");) protected void finalize () (if (! gcrun) (gcrun = true; System.out.println ( "Beginning to finalize after" + + created "Chairs have been created");) if (i == 47) (System.out.println ( "Finalizing Chair # 47," + "Setting flag to stop Chair creation"); f = true;) finalized + +; if (finalized> = created) System.out. println ( "All" finalized + + "finalized");)) public class Garbage (public static void main (String [] args) (if (args.length == 0) (System.err.println ( "Usage: \ n "+" java Garbage before \ n or: \ n "+" java Garbage after "); return;) while (! Chair.f) (new Chair (); new String (" To take up space ");) System.out.println ( "After all Chairs have been created: \ n" + "total created =" + + Chair.created "total finalized =" + Chair.finalized); if (args [0]. equals ( " before ")) (System.out.println (" gc ():"); System.gc (); System.out.println ( "runFinalization ():"); System.runFinalization ();) System.out. println ( "bye!"); if (args [0]. equals ( "after")) System.runFinalizersOnExit (true);))
The above procedure to create many Chair object, and refuse collection in the running for some time, the program will stop creating Chair. As refuse collection device may run at any time, so we can not know exactly when it started. Therefore, the procedures use a marker called gcrun to point out that the garbage collectors have started operation. Use second marker f, Chair can tell main () it should stop targeting Generation. These two markers are in finalize () internal settings, which call at the refuse collection period. The other two static variables - created and finalized - were used to track the number of objects have been created, as well as refuse collection has been End completion of the work of the number of objects. Finally, each has its own Chair (non-static) int i, so it can track what is the specific code. No. 47 Chair End relevant work carried out after the marker will be set to true, and ultimately the end of the creation of object Chair. (On the example of the more specific analysis and see "Java programming thinking," the fourth chapter)
5 on the refuse collection points added
After the above note, we find that recycling has the following characteristics:
(1) refuse collection in unpredictable: as a result of different garbage collection algorithm and the use of different mechanisms for the collection, so it may be a timing, it is possible when a system is idle CPU resources when, but also and the original may refuse collection, until a limit memory consumption, when this and refuse collection and the choice of specific settings have relations.
(2) the accuracy of refuse collection: including two major aspects: (a) refuse collection will be able to accurately target marker alive; (b) refuse collection will be able to accurately position the application of relations between objects. The former is completely recover all the prerequisite abandoned objects, otherwise we may cause memory leaks. While the latter is to achieve merge replication algorithm and the necessary conditions. Not all up to object to be reliable recovery, all objects are able to redistribute, allowing the replication objects, and objects of memory and shrink, thus effectively prevent the fragmentation of memory.
(3) There are many different types of refuse collection, each has its different algorithm and its performance, both when the refuse collection at the beginning of the application process to stop the operation, there at the beginning when the refuse collection also allows application threads running, and at the same time refuse collection multi-threaded operation.
(4) refuse collection and the realization of specific JVM and JVM memory model has a very close relationship. Different JVM may adopt different garbage collection, and JVM memory model determines the JVM can be used which types of refuse collection. Now, HotSpot JVM series in the memory system is the use of advanced object-oriented framework for the design, which makes the series JVM can adopt the most advanced of the refuse collection.
(5) With the development of modern technology to provide many refuse collection optional garbage collection, but also in the allocation of time for each collection can be set up with different parameters, it is based on different application environment was the most superior application performance possible.
In view of the above characteristics, we use the time to pay attention to:
(1) Do not try to assume that the time of refuse collection, which are all unknown. For example, the method of a temporary object method call in the end become useless after object, and this time its memory can be released.
(2) Java in a number of refuse collection and dealing with the class, but also provides a forced implementation of refuse collection method - calling System.gc (), but it is uncertain way. Java does not guarantee that each invocation of the method they will be able to start garbage collection, it will only issue such a JVM to the application, in the end whether to implement garbage collection, everything is uncertain.
(3) selection of their own garbage collector. Generally speaking, if the system is not unique and demanding performance requirements, can be used JVM the default option. Otherwise, consider using targeted refuse collection, such as incremental collection on more suitable for real-time systems require higher. System configuration with a higher, more idle resources, consider using parallel marking / removal of the collector.
(4) is difficult to understand the key issue is memory leakage. Good programming practices and rigorous programming attitude is always the most important, and not let our memory a small mistake led to a big loophole.
(5) early release useless object. Most programmers in the use of temporary variables, the variables are used to withdraw from activities in the domain (scope), automatically set to null, that garbage collectors to collect the object, we must also pay attention to whether the object was quoted eavesdropping, If so, would remove the sniffers, and then conferred null value.
6 CONCLUSION
Generally speaking, Java developers can not attach importance to the JVM heap memory allocation and garbage collection, however, fully understand the characteristics of the Java allows us to make more efficient use of resources. At the same time we should pay attention to finalize () method is the default mechanism for Java, and sometimes targeted resources to ensure the release of the clear, can finalize their preparation methods.
</ Td> </ tr> <tr>
↑ Back
Tags: Collection, java Collection






