[Effective Java] Item 8 – Avoid finalizers and cleaners

Published by

on

What are finalizers and cleaners?

  • Finalizers are the methods that get invoked by JVM garbage collector before the instance gets removed from the memory.
  • From Java 9+, Cleaners are introduced and are just the same as Finalizers but overcome some of the defects of the Finalizers.

Usage of finalizers

Figure 1. Usage of finalizers
  • By declaring finalize() method, the GC will consider that method to be executed when it cleans up the garbages.
  • But note that finalize() method makes it to be garbage collection target, but do not guarantee when it’ll be executed. It may and may not be executed.

Disadvantage of finalizers

  1. We don’t know when it’ll be executed.
    • It is possible it might not be executed at all.
    • That’s why we should never run tasks that are crucial from the finalizers and cleaners.
  2. Delays the memory cleanup + Low performance
    • Finalizer threads have a low priority, so we don’t know when the GC will execute those codes. With that being said, the memory that’s held by the method will not be retrieved until GC executes it.
    • Implement AutoClosable or use try-with-resource instead.
  3. Security breaches
    • As seen from the below Figure 2, by using the fact that finalizer gets called even though exception occurs, invalid instance can still access the data from the finalizer.
Figure 2. Finalizer Attack
  • Implement AutoClosable interface and use try-with-resources to return resources.
Figure 3. try-with-resources and AutoCloseable

Also, adding Finalizer and Cleaner to the SampleResource class of Figure 3 as a safety net just to make sure the close() method gets called(Just for double check purpose) can be preferred as well.

Reference

Leave a comment