Understanding Java Garbage Collection _java

Source: Internet
Author: User
Tags garbage collection int size throwable

When a program creates an object, an entity of a reference type, such as an array, the system allocates a piece of memory to this object in heap memory, which is stored in this memory, which becomes garbage when it is no longer referenced by any reference variable, and waits for the garbage collection mechanism to be recycled. The garbage collection mechanism has three characteristics:

The garbage collection mechanism is responsible for reclaiming only the objects in the heap memory. Does not reclaim any physical resources (such as database connections, open file resources, etc.), nor does it reclaim the memory allocated for that pair in a manner other than the way in which the object was created (for example, the memory requested by the object to invoke malloc in the local method)
The program cannot precisely control the operation of garbage collection, it can only recommend garbage collection, there are two types of System.GC () and Runtime.getruntime () in the suggested way. GC ()
The Finalize () method of a garbage collection is always invoked before any object is reclaimed, but the timing of the call to the Finalize () method is uncertain when the time for garbage collection is the same.
For the above three features, there are three questions:

1. Cleaning must be done manually, freeing memory and other physical resources allocated in ways other than the way in which objects are created. Also, be aware of eliminating outdated object references, which may cause oom.

Manual cleanup is usually used to try...finally ... Such a code structure.

Examples are as follows:

Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;

public class Manualclear {public

 static void Main (string[] args) {
  FileInputStream fileinputstream = null;
  try {
   FileInputStream = new FileInputStream ("./src/manualclear.java");
  } catch (FileNotFoundException e) {
   System.out.println (E.getmessage ());
   E.printstacktrace ();
   return;
  }

  try {
   byte[] bbuf = new byte[1024];
   int hasread = 0;
   try {
    while (Hasread = Fileinputstream.read (bbuf)) > 0) {
     System.out.println (new String (bbuf, 0, Hasread)) ;
    }
   }  catch (IOException e) {
    e.printstacktrace ();
   }
  }} finally {
   try {
    fileinputstream.close ()
   } catch (IOException e) {
    e.printstacktrace ();}}}


For a reference to an expired object, the resulting oom usually has three common situations, and these three cases are often difficult to find, running in a short period of time will not have any problems, but after a long time, the leakage of objects will eventually cause the program crash.

Beware of memory leaks when classes manage memory themselves
Examples are as follows:

 import java.util.Arrays; import java.util.EmptyStackException;
 Class stack{private object[] elements;
 private int size;
 
 private static final int default_inital_capacity = 16;
 Public Stack () {elements = new object[default_inital_capacity];
  public void push (Object e) {ensurecapacity ();
 elements[size++] = e;
  Public Object Pop () {if (size = = 0) {throw new emptystackexception ();
 return elements[--size]; 
  private void Ensurecapacity () {if (elements.length = = size) {elements = arrays.copyof (elements, 2 * size + 1);
  
  }} public class Stackdemo {public static void main (string[] args) {Stack stack = new Stack ();
  for (int i = 0; I < 10000 i++) {Stack.push (New Object ());
  for (int i = 0; I < 10000 i++) {Stack.pop (); }
 }

}

Memory leaks are due to objects that stack up even though other objects are no longer referenced, but the elements[in the stack class still holds references to those objects, causing them not to be reclaimed by garbage collection, so when the class needs to manage its own memory, Be aware that these expired references to internal maintenance are being lifted in time, in this case, only after the stack is displayed

Elements[size] = null;

Caching is to be wary of memory leaks
This usually occurs when the object is put into the cache, it is likely to be used for long periods of time is easy to forget, you can usually use Wakehashmap to represent the cache, after the items in the cache expire, they can be automatically deleted. Or it can be performed periodically by a background thread to clear expired items in the buffer.

The registration of a listener or callback, preferably the cancellation registration that can be displayed.
2, do not manually call Finalize (), it is called to the garbage collector

3, avoid using the Finalize () method, unless you use it as a judgment termination condition to discover parts of the object that are not properly cleaned up, and to clean up the system resources as a safety net while manually cleaning the forgotten calls, delaying the cleanup is never a good thing, and if you record the information that you forgot to clean up the resources, Also easy to find errors later, and timely change forgotten to clean up the code, the local method to release the object is not a very critical system resources.

The Finalize () method is not guaranteed to be accurate because of its execution time and whether it is determined to be executed, so it is best not to release critical resources, but it can be used for the three scenarios described above. The first of these cases is the following example:

Class Book {
 Boolean checkout = false;
 Public Book (Boolean checkout) {
  this.checkout = checkout;
 }
 
 public void Checkin () {
  checkout = false;
 }
 
 @Override
 protected void Finalize () throws Throwable {
  if (checkout) {
   System.out.println ("Error:check Out ");

}}} public class Finalizecheckobjectuse {public

 static void Main (string[] args) {
  new book (true);
  System.GC ();
 }


Execution results:

Error:check out
The book object in the example must be in a checkin state before it is released, otherwise it cannot be released, and the implementation in finalize can help to detect the illegal object in time or, more directly, use a reference variable reference directly in Finalize. Bring it back into the reachable state, and then process it again.

Another point to note is that if the subclass overrides the Finalize method of the parent class, But forgetting to manually invoke the Super.finalize or subclass's finalize process when an exception results in a failure to super.finalize, the parent class's finalization method will never be transferred.

As follows:

Class parent{
  @Override
  protected void Finalize () throws Throwable {
    System.out.println (). GetName () + "finalize start");
  }

Class Son extends parent{
  @Override
  protected void Finalize () throws Throwable {
    System.out.println ( GetClass (). GetName () + "finalize start");
  }
public class Superfinalizelost {public

  static void Main (string[] args) {
    new Son ();
    System.GC ();
  }



Run Result:

Son Finalize Start
or

Class parent{
  @Override
  protected void Finalize () throws Throwable {
    System.out.println (). GetName () + "finalize start");
  }

Class Son extends parent{
  @Override
  protected void Finalize () throws Throwable {
    System.out.println ( GetClass (). GetName () + "finalize start");
    int i = 5/0;
    Super.finalize ();
  }
public class Superfinalizelost {public

  static void Main (string[] args) {
    new Son ();
    System.GC ();
  }


Execution results:

Son Finalize Start
for the second case, you can use try...finally ... Structure, but for the first case, it is best to use a way called the End method keeper. Example below

Class parent2{
  private final Object Finalizeguardian = new Object () {
    protected void Finalize () throws Throwable {
      System.out.println ("logic in the finalization method of the parent class");

};} Class Son2 extends parent2{
  @Override
  protected void Finalize () throws Throwable {
    System.out.println ( GetClass (). GetName () + "finalize start");
    int i = 5/0;
    Super.finalize ();
  }

public class Finalizeguardian {public

  static void Main (string[] args) {
    new Son2 ();
    System.GC ();
  }



Execution results:

This executes the logic in the parent class finalization method
Son2 Finalize Start
This ensures that the actions required in the finalization method of the parent class are executed to.

The above is the entire content of this article, I hope to help you learn.

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.