JVM garbage Collection Mechanism summary (6): Perspective Java GC Features

Source: Internet
Author: User
Tags throwable

1. Use System.GC () to request Java garbage collection regardless of which garbage collection algorithm the JVM is using. there is a parameter in the command line-VERBOSEGC can view the heap memory used by Java, its format: JAVA-VERBOSEGC classfile

1 classTESTGC {2           Public Static voidMain (string[] args) {3            NewTESTGC (); 4 System.GC (); 5 system.runfinalization (); 6        }    7     }     8  9 Ten     classTESTGC { One          Public Static voidMain (string[] args) { A         NewTESTGC ();  - System.GC ();  - system.runfinalization ();  the } -}

In this example, a new object is created, because it is not used, so the object quickly becomes accessible, after the program compiles, executes the command: JAVA-VERBOSEGC TESTGC After the result is:

[Full GC 168k->97k (1984K), 0.0253873 secs]

The environment for the machine is, Windows + JDK1.3.1, data 168K and 97K before and after the arrows represent the amount of memory used by all surviving objects before and after garbage collection GC, indicating that the 168k-97k=71k object capacity is recycled. The data in parentheses is 1984K to the total capacity of the heap memory, and the time required for collection is 0.0253873 seconds (this time will vary at each execution).

2. Finalize method to view the operation of garbage collector

Before the JVM garbage collector collects an object, it is generally required that the program call the appropriate method to dispose of the resource, but without explicitly releasing the resource, Java provides a default mechanism to terminate the object's heart release resource, which is finalize (). Its prototype is:
Java code
1. protected void Finalize () throws Throwable
After the Finalize () method returns, the object disappears and garbage collection begins execution. The throws Throwable in the prototype indicates that it can throw any type of exception.

The reason to use Finalize () is that there are times when you need to take a different approach to Java's common approach, by allocating memory to do something with C-style. This can be done primarily through "intrinsic methods", which are a way to invoke non-Java methods from Java. C and C + + are the only languages currently supported by native methods. But because they can invoke subroutines written in other languages, they are able to invoke anything effectively. Within non-Java code, you might be able to call the malloc () series of C, which allocates storage space. and unless free () is called, storage space is not freed, causing a memory "vulnerability" to occur. Of course, free () is a C and C + + function, so we need to call it in an intrinsic method inside Finalize (). This means that we cannot use Finalize () too much, and it is not an ideal place to do normal cleanup work.

In normal cleanup, to clear an object, the user of that object must invoke a purge method at the point where it is expected to be cleared. This is somewhat inconsistent with the concept of C + + "sabotage". In C + +, all objects are destroyed (cleared). Or, in other words, all objects "should" be destroyed. If you create a C + + object as a local object, such as in the stack (which is not possible in Java), the cleanup or destruction will be done at the end of the scope of the object that the "closing curly brace" represents. If the object is created with new (similar to Java), then when the programmer calls the C + + DELETE command (Java does not have this command), the corresponding destroy is invoked. If the programmer forgets, then never call the destruction, we will end up with a memory "vulnerability", also including the other parts of the object will never be erased.

Instead, Java does not allow us to create local (local) objects-in any case, using new. In Java, however, there is no "delete" command to dispose of objects, because the garbage collector helps us to automatically free up storage space. So if we stand in a relatively simplified position, we can say that there is a garbage collection mechanism, so Java does not have a destruction device. However, with further study, you will know that the existence of the garbage collector does not completely eliminate the need for the destruction, or the need to eliminate the kind of mechanism that the device represents (and definitely not directly call Finalize (), so try to avoid using it). If you want to perform some sort of cleanup work other than freeing the storage space, you still have to call one of the methods in Java. It is equivalent to C + + 's destruction, but not the latter convenience.

The following example shows you the process of garbage collection and summarizes the previous statements.

1  Packagehr.test; 2       3 ImportJava.util.Calendar; 4       5      classChair {6         Static intcreated = 0;//Object Creation Count7         Static intfinalized = 0;//Object Recycle Count8         //Constructors9 Chair () {Tencreated++;  OneSystem.err.println ("Created" +created+ "" "" "+calendar.getinstance (). Get (Calendar.minute) +" M "+calendar.getinstance ( ). Get (Calendar.second) + "s" ");  A         }   -         //garbage Collection destructor -         protected voidFinalize () { thefinalized++;  -System.out.println ("Finalize" +finalized+ "" "+calendar.getinstance (). Get (Calendar.minute) +" M "+ Calendar.getinstance (). Get (Calendar.second) + "s" ");  -         }   -     }   +        -      Public classGarbage { +          Public Static voidMain (string[] args) { A              while(chair.created!=10000) {   at                 NewChair ();//Creating Objects -             }   -              while(true){   -                 if(chair.created==10000){   -                      Break;  -                 }   in             }   -         }   to}

The above program creates 10,000 chair objects. However, it was found in the running results that when the cumulative loop was created to X objects, we found that the main thread was suspended and the JVM started to run the garbage collection program. The evidence is that the screen begins to print "final ...". And the main thread is suspended time is uncertain, sometimes we can even see in the output half "create. "It begins to print" final ... ".

After the above description, you can find that garbage collection has the following characteristics:

(1) The unpredictable nature of garbage collection: Due to the implementation of different garbage collection algorithms and the use of different collection mechanisms, it may be timed to occur, it is possible to occur when the system is idle CPU resources, it may be the same as the original garbage collection, wait until memory consumption limit occurs, This is related to the choice of the garbage collector and the specific settings.

(2) The accuracy of garbage collection: mainly includes 2 aspects: (a) The garbage collector can accurately mark the living objects; (b) The garbage collector is able to pinpoint the referential relationships between objects. The former is a precondition for completely reclaiming all discarded objects, or it may cause a memory leak. The latter is necessary for the realization of algorithms such as merging and copying. All unreachable objects can be reliably recycled, all objects can be reassigned, objects are copied and object memory is shrunk, which effectively prevents fragmentation of memory.

(3) There are many different kinds of garbage collectors, each with its algorithm and its performance, both stopping the application when garbage collection starts, and allowing the application's thread to run when garbage collection starts, as well as the garbage collection multithreading at the same time.

(4) The implementation of garbage collection is closely related to the specific JVM and the JVM's memory model. Different JVMs may have different garbage collections, and the JVM's memory model determines what types of garbage collection the JVM can take. The memory systems in the HotSpot family of JVMs are now designed with an advanced object-oriented framework, allowing the JVM to use state-of-the-art garbage collection.

(5) With the development of technology, modern garbage collection technology provides many optional garbage collectors, and in the configuration of each collector can also set different parameters, which makes it possible to obtain the best application performance according to the different applications environment.

In view of the above characteristics, we should pay attention to when using:

(1) Do not attempt to assume that garbage collection occurs at any time, all of which are unknown. For example, a temporary object in a method becomes a useless object when the method call is complete, and its memory can be freed at this time.

(2) Java provides a number of classes that deal with garbage collection, and provides a way to enforce garbage collection-calling System.GC (), but this is also an indeterminate approach. Java does not guarantee that each call to this method will be able to start garbage collection, it will only issue to the JVM such a request, whether or not to actually perform garbage collection, everything is unknown.

(3) Pick a garbage collector that suits you. In general, if your system does not have special and demanding performance requirements, you can use the JVM's default options. Otherwise, you might consider using a targeted garbage collector, such as an incremental collector, which is more suitable for systems with higher real-time requirements. The system has a high configuration, there are more idle resources, you can consider using the parallel tag/purge collector.

(4) The key is also difficult to grasp the problem is the memory leak. Good programming habits and rigorous programming attitude is always the most important, do not let your own a small error caused a large memory leak.

(5) Release the reference of the useless object as soon as possible. Most programmers use temporary variables when the reference variable is automatically set to null after exiting the active domain (scope), implies that the garbage collector collects the object, and must be aware that the referenced object is listening, and if so, remove the listener and then assign a null value.

Conclusion

In general, Java developers can not focus on the allocation of heap memory and garbage collection in the JVM, but fully understanding the Java feature allows us to use resources more efficiently. Also note that the Finalize () method is the default mechanism for Java, and sometimes you can write your own Finalize method to ensure explicit release of object resources.

JVM garbage Collection Mechanism summary (6): Perspective Java GC Features

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.