Java's garbage mandatory recycling

One o'clock eye

When an object loses reference to the system when to call its finalize () method to clean up its resources, when it may become unreachable state, when the system recover its occupied memory for program fully transparent. Program can only control one object is no longer referenced by any reference variables, can not control it when it was recovered.

Program can force a garbage collection system - this is only mandatory notification system for garbage collection, but the garbage collection system is still not sure. Most of the time, the program mandatory garbage collection always has some effect

Mandatory garbage collection system has the following two methods:

  • Call gc System class () static method: System.gc ()

  • Runtime object call GC () Example Method: Runtime.getRuntime () gc ().

The second does not force a garbage collection Code

Code 1

public class GcTest
{
   public static void main(String[] args)
   {
      for (int i = 0 ; i < 1; i++)
      {
         new GcTest();
      }
   }
   public void finalize()
   {
      System.out.println("系统正在清理GcTest对象的资源...");
   }
}

2 runs

The program runs without any results.

3 Description

The program creates an anonymous object that is created immediately after entering the recoverable state, wait for the system recovery, but until the program exits, the system still can not recover the resource.

Three mandatory garbage collection Code

Code 1

public class GcTest
{
   public static void main(String[] args)
   {
      for (int i = 0 ; i < 1; i++)
      {
         new GcTest();
         // 下面两行代码的作用完全相同,强制系统进行垃圾回收
         // System.gc();
         Runtime.getRuntime().gc();
      }
   }
   public void finalize()
   {
      System.out.println("系统正在清理GcTest对象的资源...");
   }
}

2 runs

系统正在清理GcTest对象的资源...

3 Description

The printing instructions mandatory garbage collection played a role.

After execute the following command-line statement, you can see the first garbage collection, the memory occupied by the contrast recovery.

E:\Java\IDEA_Java\out\production\IDEA_Java>java -verbose:gc GcTest
[GC (System.gc())  2621K->760K(251392K), 0.0009908 secs]
[Full GC (System.gc())  760K->670K(251392K), 0.0040659 secs]
系统正在清理GcTest对象的资源...

Operation has demonstrated that the effect of the program mandatory garbage collection, but this is only recommended mandatory garbage collection system immediately, the system is entirely possible not immediately garbage collection, garbage collection will not have recommended the program completely ignored; garbage collection Only after receiving the notification, garbage collection as soon as possible.

Guess you like

Origin blog.csdn.net/chengqiuming/article/details/92376879