A summary of the Java GC mechanism and the object Finalize method

Source: Internet
Author: User
Tags try catch

GC is the meaning of garbage collection (garbage Collection), memory processing is where programmers are prone to problems, forgetting or wrong memory recycling can cause program or system instability or even crashes, The GC functionality provided by Java can automatically monitor whether an object exceeds the scope to automatically reclaim memory.

    a graph garbage collection mechanism. NET garbage collection uses reference counting, Java's garbage collection mechanism takes a directed graph to implement, in particular, the Java program of each thread object can be regarded as a point of view of the beginning of the graph, there is an edge from the reference in the stack to the reference object in the heap. In this graph, if an object and the root node are accessible, then the object is valid, and conversely, the object can be recycled. The advantage of adopting such a mechanism is that it can effectively avoid circular references.   When a programmer creates an object, the GC starts to monitor the address, size, and usage of the object. Determine which objects are "unreachable" through the graph-based mechanism and which objects are "inaccessible". When the GC determines that some objects are unreachable, it is the GC's responsibility to reclaim those memory spaces.    GC is usually implemented by one or a group of threads in the JVM, which itself occupies the same heap space as the user program and consumes the CPU at runtime. When the GC process runs, the application stops running. To prevent the exceptions thrown by the finalize function from affecting the operation of the garbage collection thread, the garbage collection thread makes a try catch when each finalize function is called, discards the exception if it is caught, and then processes the finalize function of the next defunct object. Therefore, it is generally necessary to handle the thrown exception within the Finalize function to prevent an unhandled exception from occurring.    when the GC is running longer, the user can feel the Java program's pause, on the other hand, if the GC runs too short, the object recovery may be too low, which means that many objects that should be recycled are not recycled and still occupy a lot of memory. So a compromise scheme is to process a certain proportion of the object each time the GC is divided into several times, which is called an incremental GC.   GC 1) In young generation, there is a space in the Eden space, mainly for the new objects, and two survivor Spaces (from and to), their size is always the same, They are used to store objects that survive each garbage collection.  2) in old generation, it primarily stores memory objects that have a long life cycle in the application.  3) in young generation block, garbage collection is generally used copying algorithm, fast. At each GC, the surviving objects are first copied from Eden to a survivorspace, and when the survivor space is full, the remaining live objects are copied directly to Oldgeneration. So, the Eden memory block is emptied after each GC.  4) in the old generation block, garbage collection generally uses the mark-compact algorithm, slower, but reduces memory requirements.  5) Garbage collection sub-level, 0 level for all (full) garbage collection, the old section of garbage collection, 1 or more of the garbage collection, will only recover the garbage in young, memory overflow usually occurs after the old or perm segment garbage collection, There is still no memory space to accommodate new Java objects.        GC only reclaims the heap area's memory, that is, processing Java new objects, but cannot close other resources, and cannot handle the memory allocated by Java call C or other languages.    if the object's Finalize function is called, the object is in an unreachable state, and the GC prepares to reclaim the memory of the object, that is, the call to the Finalize function occurs before the memory is reclaimed.   JVM does not guarantee that the Finalize function is necessarily called. The System.runfinalizersonexit method is unsafe and obsolete, and all does not guarantee that a finalize function will be called when the program exits. In addition, the specification guarantees that the Finalize function runs at most once.   SYSTEM.GC does not guarantee that the GC executes, but sends a recommendation to the JVM, not a command. The    object is unreachable, but it becomes reachable after the call to finalize, which allows the other handles to execute itself through the this pointer in the Finalize function, but no more calls to finalize the next time it is reclaimed, because it can only be called once. protected void Finalize () {     main.ref=this;  //restores this object so that this object can be up to}   The garbage collector cannot properly recycle classes that are written in code other than Java (such as the memory allocated by the new method of jni,c++), and it is necessary to override the default Finalize method for proper release and recycling of this part of the memory (for example, C + + requires delete).    finalize cannot be equated to a C + + object's destructor, and C + + destructors determine execution at the end of the object's life cycle, whereas the call to the Finalize function is very uncertain. Call time uncertainty-risk of resource waste   if some scarce resources are put into finalize ()Release, which could lead to the scarcity of resources that have been released for a long, long time. Cause a waste of resources! In addition, the resources that some class objects carry, such as some JDBC classes, can be very memory-intensive, and the delayed release of these resources can cause significant performance problems.   may not be called-there is a risk of resource leaks   in some cases, finalize () is not called at all. For example, when the JVM exits, the Finalize function of those objects in memory may not be called.   Therefore some cleanup work such as file closure, connection closure and so on do not put into the Finalize function, to be managed separately in the program, generally finalize only do C + + memory recycling.     even if there is a GC mechanism, there is a memory leak problem with Java 1. The static collection class forms the object reference   copy code static vector v = new vector ();  for (int i = 1; i& lt;100; i++)  {     Object o = new Object ();     V.add (o);     o = null; } copy Code 2. When the object properties inside the collection are modified, the Remove () method does not work  3. Various connections, database connections, network connections, IO connections, etc., show call close to be recycled by GC     Object references in the Java language fall into the following categories: Strong reference, soft reference, weak reference, virtual reference strong reference is the most commonly used reference, when memory space is not enough, Java virtual machine would rather throw outofmemoryerror error, so that the program terminates abnormally, It is also not easy to recycle a strongly referenced object to resolve an out-of-memory problem.   If an object has only soft references, enough memory space is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed.   Only objects with weak references have a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not.   Virtual reference, this kind of reference is not commonly used, the main purpose is the result refers to the association object, implements the object reference relation tracing. A virtual reference does not determine the life cycle of an object. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references.   Several reference pointsnot located in Java.lang.ref.SoftReference;    java.lang.ref.WeakReference; and java.lang.ref.phantomreference;    a bit of a record about the handle and the object string s = new String ("abc"); The "ABC" object is created in the text pool during the compile phase, when new is run, a copy of the object in the pool is copied into the heap, and a reference to the object in the heap is given to S hold, so this statement creates 2 string objects.  string S1 = new String ("abc"); String s2 = new String ("abc"); Create a total of three objects, one in the pool, and 2 in the heap. The   handle can exist without relying on an object, such as String s, which creates the handle S, which is saved in the stack, but does not have any objects associated with it. The handle can be considered as a remote control, the object is a TV, with a remote control, you can control the TV, but no TV, the same can have a remote control.   Because of the large use of the string object (which is an object, in general, the object always allocates memory in the heap), in Java in order to save memory space and run time, in the compilation phase of all the string literal into a text pool (pool of literal strings), The run-time text pool becomes part of the constant pool. The benefit of a text pool is that all the same string constants in the pool are merged, occupying only one space. So the above "ABC" only occupies a portion of space.  string S1 = "abc"; string s2 = "abc"; here S1 = = S2 established  string s1 = new String ("abc"); String s2 = new String ("abc"); here S1 = = S2 not established, s1.equals (S2) established     garbage collection algorithm The Java language Specification does not explicitly state which garbage collection algorithm the JVM uses, But any kind of garbage collection algorithm generally do 2 basic things: (1) Find useless Information object, (2) Reclaim the memory space occupied by the useless object, make the space can be reused by the program.   Most garbage collection algorithms use the concept of root set (root set), which is a collection of reference variables (including local variables, parameters, class variables) that are accessible to the Java program that is being executed, and the program canUse reference variables to access the properties of the object and the methods that call the object. Garbage collection preferences need to determine which ones are accessible from the root and which are unreachable, objects that can be reached from the root set are active objects, and they cannot be recycled as garbage, which also includes objects that are indirectly accessible from the root set. The root set, which is unreachable by any path, is eligible for garbage collection and should be recycled. Here are a few common algorithms. The  1, reference counting method (Reference counting Collector)   Reference counting is the only method of garbage collection that does not use the root set, which uses reference counters to differentiate between surviving objects and objects that are no longer in use. In general, each object in the heap corresponds to a reference counter. When an object is created and assigned to a variable each time, the reference counter is set to 1. When an object is assigned to any variable, the reference counter is incremented by 1 each time the object is scoped (the object is discarded), the reference counter is reduced by 1, and once the reference counter is 0, the object satisfies the garbage collection condition.   The garbage collector based on the reference counter runs faster and does not interrupt program execution for long periods of time, and it is appropriate to run the program in real time. However, the reference counter increases the cost of executing the program because each time the object is assigned to a new variable, the counter adds 1, and each time the existing object is scoped, the counter is reduced by 1. The  2, tracing algorithm (tracing Collector)  tracing algorithm is proposed to solve the problem of reference counting, which uses the concept of the root set. The garbage collector based on the tracing algorithm starts scanning from the root set to identify which objects are available, which objects are unreachable, and to mark objects in some way, such as setting one or more bits for each object that can be reached. During the scan recognition process, garbage collection based on the tracing algorithm is also known as the Mark and Purge (mark-and-sweep) garbage collector.  3, compacting algorithm (compacting Collector)   To solve the problem of heap fragmentation, garbage collection based on tracing absorbs the idea of the compacting algorithm, in which the algorithm moves all objects to one end of the heap, and the other end of the heap becomes an adjacent free memory area, and the collector updates all references to all objects it moves. This allows these references to recognize the original object in the new location. In the implementation of the collector based on the compacting algorithm, the handle and the handle table are generally added.  4, copying algorithm (coping Collector)   This algorithm is proposed to overcome the overhead of the handle and the garbage collection to resolve heap fragmentation. It begins by dividing the heap into an object face and multiple free polygons, where the program allocates space for objects from the object surface, and when the object is full, based on the COThe ping algorithm's garbage collection scans the active object from the root set and copies each active object to the free surface (so that there is no free hole between the active object's memory) so that the free surface becomes the object face, the original object face becomes the idle surface, and the program allocates memory in the new object face.   A typical garbage collection based on the coping algorithm is the stop-and-copy algorithm, which divides the heap into object and idle area polygons, and pauses execution during the switching between the object face and the idle area. One drawback of the  5, Generation algorithm (generational Collector)  stop-and-copy garbage collector is that the collector must replicate all active objects, which increases the program wait time, This is the reason why the coping algorithm is inefficient. In the program design there is such a law: most objects exist for a short time, a few of the existence of a long time. Therefore, the generation algorithm divides the heap into two or more, each sub-heap as the object's generation (generation). Because most objects exist for a shorter time, the garbage collector collects these objects from the youngest child heap as the program discards objects that are not used. After the generational garbage collector runs, the last surviving object is moved to the next highest generation sub-heap, saving time because the old generation of sub-heaps is not often recycled.  6, Adaptive algorithm (Adaptive Collector)   In certain cases, some garbage collection algorithms are better than other algorithms. The garbage collector based on the adaptive algorithm monitors the usage of the current heap and will select the appropriate algorithm for the garbage collector.

A little summary of the Java GC mechanism and object Finalize method

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.