Did you know that your Java code may be vulnerable to an exploit based on finalization? I didn’t.
This article from IBM’s developerWorks explains how it works.
Basically, you can safe a reference to an object in the finalize()
method. At this time, the object may even be in an inconsistent state (the finalizer will be called when the constructor threw an exception).
As for the solution: I don’t like it very much. It adds even more clutter to the existing code and doesn’t relay its purpose very well. Someone refactoring the code might feel tempted to remove the “useless additional constructor.” Worse, you need to do this in all your classes which check their parameters.
I would prefer a solution where the compiler or some other tool fixes these issues by generating the necessary code. Especially if you look at more complex cases: What happens if an exception is thrown at a later stage of object creation? Your code is still vulnerable but it seems to be safe. How would you know?
Maybe a better solution would be to check the heap for references to any finalized objects and throw an error “finalization failed”. But that’s probably impossible without breaking backwards compatibility.
Or Oracle could invent a better solution for the finalization problem (which is basically garbage collection for non-memory-resources) so we would not need finalizers anymore.