tutorial on using Cleaner-based finalization

Roger Riggs Roger.Riggs at Oracle.com
Wed May 3 16:04:25 UTC 2017

Hi Rick,

The general nature of changes to use the Cleaner involve factoring out 
the cleanup
code from the object being cleaned, though in many cases it does not 
require restructuring.
For example, if an object holds a reference to a network socket that 
needs to be closed
when the object is collected the socket.close() can called by the cleaner:

    Cleaner cleaner = ...;
    final Socket socket = ...;
    Object obj = ...;

    cleaner.register(obj, () -> {
    try {
         } catch (IOException ioe) { // ignore}

Creating a cleaner starts a thread that does the work so you'll want to 
how to share it across the uses or to use than one.

Using lambdas for the cleaner functions is very lightweight but be 
careful to avoid
the using bound variables in the lambda body because they implicitly retain
a reference to the enclosing instance which will prevent the instance 
from becoming unreferences.

If there are more specific cases of interest let me know,

Regards, Roger

On 5/2/2017 10:08 PM, Rick Hillegas wrote:
> When I compile Apache Derby using JDK 9 build 167, I see several 
> instances of the following warning:
>    warning: [deprecation] finalize() in Object has been deprecated
> The javadoc for java.lang.Object.finalize() suggests that affected 
> classes should migrate their finalization to a coding pattern based on 
> the newly introduced java.lang.ref.Cleaner class. I am hesitant to try 
> my hand at this without more guidance. Can you point me at a tutorial 
> or list of best practices for implementing Cleaner-based finalization?
> Thanks,
> -Rick

More information about the core-libs-dev mailing list