How to ensure finalize() is always called (Thinking in Java exercise)

前端 未结 5 849
情深已故
情深已故 2020-12-10 03:51

I\'m slowly working through Bruce Eckel\'s Thinking in Java 4th edition, and the following problem has me stumped:

Create a class with a fina

5条回答
  •  臣服心动
    2020-12-10 03:58

    When the garbage collector finds an object that is eligible for collection but has a finalizer it does not deallocate it immediately. The garbage collector tries to complete as quickly as possible, so it just adds the object to a list of objects with pending finalizers. The finalizer is called later on a separate thread.

    You can tell the system to try to run pending finalizers immediately by calling the method System.runFinalization after a garbage collection.

    But if you want to force the finalizer to run, you have to call it yourself. The garbage collector does not guarantee that any objects will be collected or that the finalizers will be called. It only makes a "best effort". However it is rare that you would ever need to force a finalizer to run in real code.

提交回复
热议问题