I recommend really trying not to use finalizers or cleaning products. Create an AutoCloseable class and do any cleanup in the close() method.
Cleaners are an attempt to have a finalizer, such as a routine, that is less susceptible to finalizer attacks. But Cleaners are very difficult to write correctly.
What is a Finalizer attack?
The finalizer is launched even when the object is not completely constructed (for example, if it throws an exception inside the constructor). An attacker can subclass your vulnerable class and override its finalize method, possibly bypassing security checks or invariants made inside the constructor.
So why use a cleaner.
- Doesn't pollute the public class API (since cleaners and related objects are closed)
You do not need to create an empty final finalize method, even if you do not need it, to prevent subclasses from being overridden as part of the attack.Prevents Finalizer attacks.- The cleaner only works once
EDIT: after reviewing, I realized that Cleaners do not prevent a finalizer attack. Therefore, even if you use a cleaner in a class other than the final, create an empty final finalize method.
source share