JAVA garbage collection mechanism principle __java

Source: Internet
Author: User
Tags throwable

Here, I do not have a theoretical way to describe the principle of garbage collection mechanism. I have only 2 simple programs to explore my understanding of the Java garbage collection mechanism. After all, many things, theoretical terminology may not be intuitive to test better.

Package cn.vicky.chapt14; /** * * @author Vicky.H/public class Finalizetest {public static void main (string[] args) throws Interrupt
        
        Edexception {Session Sessions = new Session ();
        object[] arr1 = new OBJECT[5];
        
        object[] arr2 = new OBJECT[10];
        System.out.println (Session.hashcode ());
        ARR1[3] = session;
        System.out.println (Arr1[3].hashcode ());
        ARR2[7] = session;
        
        System.out.println (Arr2[7].hashcode ());
    
        System.out.println ("--------------");
        session = NULL;
        System.out.println (Arr1[3].hashcode ());
        System.out.println (Arr2[7].hashcode ());
        System.GC ();
        
        System.out.println ("First Destruction session");
        System.out.println ("--------------");
        ARR1[3] = null;
        System.GC ();
        System.out.println ("Second destruction session");
        System.out.println (Arr2[7].hashcode ());
        System.out.println ("--------------"); ARR2[7] = Null
        System.GC (); System.out.println ("Third destruction session.") Visible, "+" can be destroyed by garbage collection mechanism when the object in memory is not pointing to any of the Java programs. Note that the print statement, although executed sequentially in the Syste
                M.GC () is executed after "+", but has been printed before printing \ "Destroy object \" to indicate that System.GC () is asynchronous. "
        + "Its execution does not affect the execution of the main program, it will be handed to the JVM virtual machine for execution!");
        Thread.Sleep (30000); System.out.println ("Summary: Java cannot destroy an object as C or C + + through free () Delete, but Java can use" + "to cancel all references to \" Object \ "and call System.GC () to enter
        Row destroys. ");
    System.out.println ("Test over");
    class Session {int id;

    String name;
        @Override protected void Finalize () throws Throwable {System.out.println ("destroy object");
    Super.finalize ();
 }
}


Run-single:
33263331
33263331
33263331
--------------
33263331
33263331
First Destruction session
--------------
Second destruction session
33263331
--------------
The third time the session was destroyed. It can be seen that the object is being destroyed by the garbage collection mechanism when the object in memory is not pointing to any of the Java programs. Note that the print statement, although executed after System.GC (), is printed with "Destroy Object" It has been printed before, indicating that System.GC () is asynchronous. Its execution does not affect the execution of the main program, it will be handed to the JVM virtual machine for execution!
Destroying objects
Summary: Java cannot destroy an object as C or C + + through free () Delete, but Java can destroy it by canceling all references to "objects" and invoking System.GC ().
Test over

Package cn.vicky.chapt14;

/**
 *
 * @author Vicky.H
/public class FinalizeTest2 {public
    
    static void SayHello1 () {
        System.out.println ("Hello World". Hashcode ());
    }

    public static void SayHello2 () {
        System.out.println ("Hello World". Hashcode ());
        System.GC ();
    }
    
    public static void Main (string[] args) {
        //SayHello1 ();///Multiple execution of the program. Print results are the same: 1794106052
        SayHello2 (); Even if System.GC () is invoked, the program is executed more than once. Print results are the same: 1794106052, garbage collection is not useless?
        
        System.out.println ("Summary: Simply put, the JVM garbage collection mechanism is suitable for objects created through new, in-depth understanding can be consulted \" heap \ "and \" "Stack \");
    }
}


From the example above, we learned that System.GC () destroys data in memory without any references (pointers to) in the Java program. So how do you dereference it?

In general, objects are referenced as follows

session S; Null pointer

s = new session ()//s becomes pointer to reference

By canceling the reference to the new session (), you can turn s again into a null pointer, which is s = null, so the JVM becomes clear that the memory allocated by the new session () is garbage, and can be destroyed by System.GC ().

However, a reference to an object is saved in an array or container, or referenced in another object. We can achieve the effect through the following examples.

Package cn.vicky.chapt14;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import Java.util.Iterator;

Import java.util.List; /** * * @author Vicky.H/public class FinalizeTest1 {public static void Test1 () {player[] players = NE
        W PLAYER[10];

        Arrays.fill (Players, New Player ());
        System.out.println ("-------");
        System.out.println (Players.hashcode ());

        System.out.println (Arrays.hashcode (players));
        System.out.println ("-------");
        for (Player player:players) {System.out.println (Player.hashcode ());
        } System.out.println ("-------");
        for (int i = 0; i < players.length i++) {players[i] = new Player (); } System.GC ();
        Reclaims the player object created for the first time but not referenced.
        for (Player player:players) {System.out.println (Player.hashcode ());
        } System.out.println ("-------"); System.GC (); Attempts to recycle all objects in the players.
        [Will not be recycled] System.out.println ("Not to be recycled");
        System.out.println ("-------");
        Arrays.fill (players, NULL); System.GC (); Attempts to recycle all objects in the players.

    [Recycle succeeded]} public static void Test2 () throws Interruptedexception {list<player> players = new Arraylist<player> (
        ); System.out.println (Players.hashcode ());
        1 for (int i = 0; i < i++) {Players.add (New Player ());
        } System.out.println (Players.hashcode ());
        System.out.println ("-------");
        for (Player player:players) {System.out.println (Player.hashcode ());
        } System.out.println ("-------"); System.GC ();
        Failed to reclaim an object in the collection.
        Arrays.fill (Players.toarray (), NULL); System.GC ();

        
        Failed to reclaim an object in the collection because the Collection.toarray () is implemented through "copy" mode.
        System.out.println ("-------");
       
        Thread.Sleep (5000);
        System.out.println ("Purge part of data"); Empty part of the data list<player> sublist = Players.sublist (2, 4);The data points to the same address as the original data for (Player player:sublist) {System.out.println (Player.hashcode ()); }//Players.removeall (sublist); Cannot be thrown java.util.ConcurrentModificationException sublist.clear () by such a way;
        
        In this way, can directly modify the players.
        
        System.GC ();
        Thread.Sleep (5000);
        System.out.println ("Clear All data"); Players.clear ();
    Clear all data System.GC ();
        public static void Main (string[] args) throws Interruptedexception {//Finalizetest1.test1 ();
    Finalizetest1.test2 ();
    } class Player {int id;

    String name;
        @Override protected void Finalize () throws Throwable {System.out.println ("destroy object");
    Super.finalize ();
 }
}


 

Package cn.vicky.chapt14; /** * * @author Vicky.H/public class FinalizeTest3 {public static void main (string[] args) throws Interrup
        tedexception {/* A A = new A (new B ());
        System.GC ();
        
        SYSTEM.OUT.PRINTLN ("There are references, cannot be destroyed!");
        System.out.println ("--------");
        Thread.Sleep (5000);
        A = null;
        System.GC ();
        
        System.out.println ("There is no reference, you can destroy the destruction, because B's reference is based on a, so, when a does not refer to the automatic Association to B and no reference, then B will be destroyed!");
        System.out.println ("--------");
         Thread.Sleep (5000);
        * * B = new B ();
        A a1 = new A (b);    A a2 = new A (b); A1,A2 also references b = null;
        This simply sets B as a null pointer, but cannot modify the A1,A2 to the memory that has been created.
        System.out.println (A1.b.hashcode ());
        
        System.out.println (A2.b.hashcode ());
        A1 = null; System.GC ();
        
        Destroy the A1. But the B object will not be destroyed because A2 also retains the reference Thread.Sleep (5000) of B;
        A2 = null; System.GC (); Destroy the A2. B objects will also be destroyed because A1, a2 are destroyed and B has no references in the program.
    Class A {int id;
    String name;

    b b;
    Public A () {} public A (b b) {this.b = b;
        @Override protected void Finalize () throws Throwable {System.out.println ("destroy a object");
    Super.finalize ();
    Class B {int id;

    String name;
        @Override protected void Finalize () throws Throwable {System.out.println ("destroy a B object");
    Super.finalize ();
 }
    
}


 

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.