Debaug
Debaug

Reputation: 517

Java 9 Cleaner & Cleaner.Cleanable objects

I need to use a native pointer (an int) for an LWJGL project, and the tutorial I'm following proposes to use the Object.finalize() method. But, since it's deprecated since Java 9, I looked for better solutions. I found the Cleaner/Cleanable duo on the Oracle documentation and tried to use it, but I don't know if I'm doing it right. Is this the way to go?

import java.lang.ref.Cleaner;

public class PointerUsingObject
{
    // A native pointer
    private int pointer;
    
    private static final Cleaner cleaner = Cleaner.create();
    private final Cleaner.Cleanable cleanable;

    public PointerUsingObject()
    {
        cleanable = cleaner.register(this, new Runnable()
        {
            @Override
            public void run()
            {
                // Free the pointer
            }
        });
    }
    
    
    // Is called to destroy the object when I'm sure not to use it anymore
    public void destroy()
    {
        cleanable.clean();
    }
}

Upvotes: 1

Views: 753

Answers (1)

Debaug
Debaug

Reputation: 517

OK, so as someone pointed out, I should instantiate a static nested class to manage the cleaning, as following:

import java.lang.ref.Cleaner;

public class PointerUsingObject implements AutoCloseable
{
    // A native pointer
    private int pointer;
    
    private static final Cleaner cleaner = Cleaner.create();
    private final Cleaner.Cleanable cleanable;

    public PointerUsingObject()
    {
        cleanable = cleaner.register(this, new CleanMethod(pointer));
    }

    @Override
    public void close() throws Exception
    {
        cleanable.clean();
    }
    
    private static class CleanMethod implements Runnable
    {
        private int pointer;
        
        public CleanMethod(int pointer)
        {
            this.pointer = pointer;
        }
        
        @Override
        public void run()
        {
            // Free the pointer
        }
    }
}

I also implemented the AutoCloseable interface and replaced the destroy() method with the close() method.

Upvotes: 2

Related Questions