The Finalize method for Java uses

Source: Internet
Author: User

1. The role of Finalize

    • Finalize () is the protected method of object, which can be overridden by subclasses to implement resource cleanup, which is called by the GC before it reclaims the object.
    • Finalize () does not correspond to destructors in C + +. The timing of a destructor call in C + + is deterministic (the object leaves scope or delete), but the call to finalize in Java is nondeterministic
    • The Finalize method is not recommended for "non-memory resource" cleanup, but is recommended for: ① Cleanup of local objects (objects created by JNI); ② as a guarantee for certain non-memory resources (such as sockets, files, etc.) A supplement to release: explicitly call other resource-freeing methods in the Finalize method. The reasons for this can be seen below [finalize questions]
2. Finalize issues
    • Some finalize-related methods, due to some fatal flaws, have been deprecated, such as the System.runfinalizersonexit () method, the Runtime.runfinalizersonexit () method
    • The System.GC () and system.runfinalization () methods increase the chance for the Finalize method to execute, but not blindly rely on them
    • The Java language specification does not guarantee that the Finalize method will be executed in a timely manner and will not guarantee that they will be executed at all.
    • The Finalize method may cause performance problems. Because the JVM typically completes finalize execution in a separate low-priority thread
    • Object regeneration problem: In the Finalize method, objects to be recycled can be assigned to a GC Roots object reference to achieve object regeneration.
    • The Finalize method is executed at most once by the GC (the user can of course manually invoke the object's Finalize method, but does not affect the GC's behavior with finalize)
3. Finalize the execution process (life cycle)

(1) First, a general description of the Finalize process: When the object becomes (GC Roots) Unreachable, the GC determines whether the object overrides the Finalize method, and if it is not overwritten, it is recycled directly. Otherwise, if the object does not perform a Finalize method, it is placed in the F-queue queue, and a low-priority thread executes the Finalize method of the object in that queue. After the Finalize method is executed, the GC will again determine whether the object is reachable or not, and if not, the object is "resurrected" if it is not reachable. (2) The specific Finalize process: The object can be made up of two states, involving two types of state space, one is the final state space F = {unfinalized, finalizable, finalized}, and the second is up to the state space R = {reachable, Finalizer-reachable, unreachable}. Each state has the following meanings:
    • Unfinalized: The new object enters this state first, and the GC is not ready to execute its Finalize method because the object is reachable
    • Finalizable: Indicates that the GC can perform a Finalize method on the object, and the GC has detected that the object is not reachable. As mentioned earlier, the GC completes finalize execution with the F-queue queue and a dedicated thread
    • Finalized: Indicates that the GC has performed a Finalize method on the object
    • Reachable: Indicates GC roots reference up to
    • Finalizer-reachable (f-reachable): Indicates not reachable, but can be reached by a Finalizable object
    • Unreachable: Objects can not be reached by the above two ways
State transition diagram: Change notes:
    1. New object First in [reachable, unfinalized] State (A)
    2. As the program runs, some referential relationships disappear, resulting in state transitions from reachable state to F-reachable (B, C, D) or unreachable (E, F) states
    3. If the JVM detects that an object in the unfinalized state becomes f-reachable or UNREACHABLE,JVM marks it as a finalizable state (g,h). If the object is originally in the [Unreachable, unfinalized] state, it is also marked as f-reachable (H).
    4. At some point, the JVM takes out a finalizable object, marks it as finalized, and executes its Finalize method in a thread. Because the object is referenced in the active thread, the object changes to the (reachable, finalized) state (K or J). This action will affect some other objects from the f-reachable state back to the reachable state (L, M, N)
    5. An object in the finalizable state cannot be unreahable at the same time, and by the 4th, the Finalizable object is marked as finalized by a thread that executes the Finalize method of the object, causing it to become reachable. That's why there are only eight status points in the diagram.
    6. The programmer's Manual call to the Finalize method does not affect the changes in the internal tags above, so the JVM will only call finalize once, even if the object is "resurrected". How many times the programmer manually calls does not affect the behavior of the JVM
    7. If the JVM detects that the finalized state object becomes unreachable, reclaims its memory (I)
    8. If the object does not overwrite the Finalize method, the JVM optimizes and reclaims the object directly (O)
    9. Note: the System.runfinalizersonexit () method allows the JVM to perform a Finalize method on the object even if it is in the reachable state
4. Some code examples
(1) Object Resurrection
  1. Public class GC {
  2. public static GC save_hook = null;
  3. public static void Main (string[] args) throws interruptedexception {
  4. Save_hook = new GC ();
  5. Save_hook = null;
  6. System.GC ();
  7. Thread.Sleep (500);
  8. if (null! = Save_hook) { //This time the object should be in the (reachable, finalized) state
  9. System.out.println ("Yes, I am still Alive");
  10. } Else {
  11. System.out.println ("No, I am Dead");
  12. }
  13. Save_hook = null;
  14. System.GC ();
  15. Thread.Sleep (500);
  16. if (null! = Save_hook) {
  17. System.out.println ("Yes, I am still Alive");
  18. } Else {
  19. System.out.println ("No, I am Dead");
  20. }
  21. }
  22. @Override
  23. protected Void Finalize () throws Throwable {
  24. super.finalize ();
  25. System.out.println ("Execute Method Finalize ()");
  26. Save_hook = this ;
  27. }
  28. }
(2) Overwrite the Finalize method to ensure that the resource release is used as a supplemental action in case the user forgets to "close" the resource, the FileInputStream, FileOutputStream, connection classes in the JDK use this "technology", The following code is excerpted from the FileInputStream class
  1. /**
  2. * Ensures that a <code>close</code> method of this file input stream is
  3. * Called when there is no more references to it.
  4. *
  5. * @exception IOException If an I/O error occurs.
  6. * @see Java.io.fileinputstream#close ()
  7. */
  8. protected Void Finalize () throws IOException {
  9. if (fd! = null) && (FD! = filedescriptor.in)) {
  10. / * If FD is GKFX, the references in FileDescriptor
  11. * Would ensure that finalizer was only called when
  12. * Safe to do. All references using the FD has
  13. * Become unreachable. We can call Close ()
  14. */
  15. Close ();
  16. }
  17. }
Reference:
12.6 Finalization of Class Instances https://notendur.hi.is//~snorri/SDK-docs/lang/lang083.htm in-depth understanding of Java Finalize Http://zhang-xzhi-xjtu.iteye.com/blog/484934The finalizable Object http://www.artima.com/interfacedesign/ Finalizable.html

The Finalize method for Java uses

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.