Comprehensive analysis of Java's garbage collection mechanism 2

Source: Internet
Author: User

Perspective Java Garbage Collection

1. Command line parameter perspective garbage collector run

2. 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, which is in the following format:

JAVA-VERBOSEGC Classfile

You can look at an example:

Class TESTGC
{
public static void Main (string[] args)
{
New TESTGC ();
System.GC ();
System.runfinalization ();
}
}

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
Shenyang 463 Plastic Surgery Hospital http://www.hengnaya.com/
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:

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 call a purge method at the point where the cleanup was made.Shenyang 463 Plastic Surgery HospitalThe program is slightly 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.

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 has 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 has 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); } 
} 

Comprehensive analysis of Java garbage collection mechanism 2

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.