Cleanup must be performed

Source: Internet
Author: User
Tags closure command line garbage collection

To clear an object, the user of that object must invoke a purge method at the location where the cleanup is desired. This may sound easy to do, but it is slightly inconsistent with the concept of C + + "sabotage". In C + +, all objects are corrupted (cleared). Or in other words, all objects are "supposed" to be corrupted. 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 work is done at the end of the scope that the end curly braces represents to create the object. If the object is created with new (similar to Java), then when the programmer invokes the C + + DELETE command (Java does not have this command), the corresponding device is invoked. If the programmer forgets, then never invokes the wreck, we end up with a memory "vulnerability" and another part of the object will never be erased.
Instead, Java does not allow us to create local (local) objects--using new anyway. In Java, however, there is no "delete" command to release objects, because the garbage collector helps us to automatically free up storage space. So if you stand in a simpler position, we can say that it is due to the existence of garbage collection mechanism, so Java does not have a broken device. However, as you learn later, 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 mechanism represented by the device (and absolutely cannot call finalize (), so try to avoid it). If you want to perform some sort of cleanup work other than freeing storage, you must still call a method in Java. It is equivalent to the C + + of the destruction, but not the latter convenient. One of the most useful places for
Finalize () is to observe the garbage collection process. The following example shows you the process of garbage collection and summarizes the previous statements.
 

: Garbage.java//demonstration of the garbage//collector and finalization class Chair {static Boolean gcrun = FA
  Lse
  static Boolean f = false;
  static int created = 0;
  static int finalized = 0;
  int i;
    Chair () {i = ++created;
  if (created = =) System.out.println ("created 47");
      } protected void Finalize () {if (!gcrun) {Gcrun = true;
    System.out.println ("Beginning to finalize" + created + "chairs have been created"); } if (i = =) {System.out.println ("finalizing Chair #47," + "Setting flag to stop Chair creat
      Ion ");
    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 Spaces");
      } System.out.println ("All chairs have 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); }
} ///:~


The above program creates many chair objects, and at some point after the garbage collector starts running, the program stops creating chair. Because the garbage collector may run at any time, we cannot know exactly when it will start. Therefore, the program uses a tag named Gcrun to indicate whether the garbage collector has started running. Using the second tag F,chair can tell main () that it should stop the object's generation. Both of these tags are set within finalize () and are used during garbage collection.
The other two static variable--created and finalized--are used to track the number of objects created and the number of objects the garbage collector has finished finishing. Finally, each chair has its own (non-static) int I, so it can track what its specific number is. Chair with number 47 finishes the finishing work, the tag is set to true, and the Chair object is eventually created.
All of this is done inside main ()--in the following loop:

while (! CHAIR.F) {
New Chair ();
New String ("to take up Spaces");
}

You may wonder when this cycle will stop because there are no statements that change the CHAIR.F value. However, the Finalize () process changes this value until the end of the object with number 47 is finalized.
The string object created during each loop is just an extra garbage that attracts the garbage collector--once the garbage collector is "nervous" about the capacity of available memory, it starts to pay attention to it.
When running this program, it provides a command line argument "before" or "after". Where the "before" argument calls the System.GC () method (which enforces the garbage collector), and the System.runfinalization () method is invoked to finish the work. These methods are available in Java 1.0, but the Runfinalizersonexit () method invoked by using the "after" argument only provides support for Java 1.1 and subsequent versions (note ③). Note You can call this method at any time the program executes, and the execution of the closure program has nothing to do with whether the garbage collector is running.

③: Unfortunately, the garbage collector scheme used by Java 1.0 never correctly calls Finalize (). As a result, the Finalize () method, especially those used to close the file, is in fact often not invoked. Now, some articles claim that all closure modules will be invoked when the program exits-even when the program is aborted, the garbage collector does not take action on those objects. This is not a real situation, so we cannot expect finalize () to be invoked for all objects. In particular, Finalize () is almost useless in Java 1.0.

The previous program revealed to us that in Java 1.1, the closure module would certainly run this promise has become a reality-but only if we explicitly force it to take this action. If you use an argument that is not "before" or "after" (such as "none"), then two finishing touches will not work, and we will get output like the following:
Created 47

Created
beginning to finalize on 8694 chairs have been Created finalizing Chair
#47, Setting flag to stop Ch Air creation after all
chairs have been created: total
created = 9834, total finalized = 108
bye!

As a result, not all closure modules are invoked (annotation ④) at the end of the program. To force closure, call System.GC () first, and then call System.runfinalization (). This clears all objects that have not been used so far. A slightly odd place to do this is to call GC () before calling Runfinalization (), which seems to contradict the Sun's documentation statement, which claims to run the closure module first and then release the storage space. However, if you first call Runfinalization () here and then call GC (), the closure module will not execute at all.

④: By the time you read this book, some Java virtual machines (JVMS) may have begun to behave differently.

For all objects, Java 1.1 sometimes defaults to skip the finishing work because it thinks it is too expensive to do so. Regardless of the method used to force garbage collection, you may notice a longer delay than when there is no extra finishing work.

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.