code example
Test1:
Public classTestClass {intFlage = 0; TestClass (intflage) {System.out.println ("New Object TestClass"); This. Flage =Flage; } @Overrideprotected voidFinalize () {System.out.println ("Run this method:finalize () and this flag is" +flage); } Public Static voidMain (string[] args) {TestClass T=NewTestClass (2); System.GC (); }}
Output Result:
New Object TestClass
Test2:
Public classTestClass {intFlage = 0; TestClass (intflage) {System.out.println ("New Object TestClass"); This. Flage =Flage; } @Overrideprotected voidFinalize () {System.out.println ("Run this method:finalize () and this flag is" +flage); } Public Static voidMain (string[] args) {TestClass T=NewTestClass (2); T=NULL; System.GC (); }}
Output Result:
New Object TestClass
Run this method:finalize () and this flag is 2
TEST3:
Public classTestClass {intFlage = 0; TestClass (intflage) {System.out.println ("New Object TestClass"); This. Flage =Flage; } @Overrideprotected voidFinalize () {System.out.println ("Run this method:finalize () and this flag is" +flage); } Static voidTest () {TestClass T=NewTestClass (3); } Public Static voidMain (string[] args) {TestClass T=NewTestClass (2); Test (); System.GC (); }}
Output Result:
New Object TestClass
New Object TestClass
Run this method:finalize () and this flag is 3
Analysis
1. Object: The scope is typically the closest one to the inside of a curly brace. Out of scope, the object continues to occupy memory space, but we cannot access the object. 2.finalize () Method: When the garbage collector is ready to release memory, Finalize () is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs. 3.system.gc () Method: This method simply recommends that the garbage collector reclaim the memory, not necessarily the actual recovery of memory. 4. When a garbage collector determines that an object is not in scope or is null, the garbage collector reclaims the object's memory (called the Finalize method). So there will be test1, Test2, Test3. (Not really aware of the garbage collector, so the single-argument program, the garbage collector will write later).
Java Finalize method