Monday 20 June 2011

Lifetime of a finalizable object

These are the steps involved in lifetime of a finalizable object:
  1. When obj is allocated, the JVM internally records that obj is finalizable. This typically slows down the otherwise fast allocation path that modern JVMs have.
  2. When the garbage collector determines that obj is unreachable, it notices that obj is finalizable — as it had been recorded upon allocation — and adds it to the JVM’s finalization queue. It also ensures that all objects reachable from obj are retained, even if they are otherwise unreachable, as they might be accessed by the finalizer.
  3. At some point later (only gc knows when), the JVM’s finalizer thread will dequeue obj, call its finalize() method, and record that the obj’s finalizer has been called. At this point, obj is considered to be finalized.
  4. When the garbage collector rediscovers that obj is unreachable, it will reclaim its space along with everything reachable from it, provided that the latter is otherwise unreachable.
Garbage collector needs a minimum of two cycles to reclaim obj and needs to retain all other objects reachable from obj during this process.

Additionally, the JVM does not guarantee that it will call the finalizers of all the finalizable objects that have been allocated. It might exit before the garbage collector discovers some of them to be unreachable.

No comments:

Post a Comment