RFR 9: 8138696 : java.lang.ref.Cleaner - an easy to use > alternative to finalization (Roger Riggs)

Mike Duigou openjdk at duigou.org
Fri Oct 2 19:33:01 UTC 2015

Hi Roger;

This looks like an interesting proposal and would be a good replacement 
for alternative solutions.

I am curious why the thread is run at max priority. Also, why not set 
priority and daemon status in the factory?

You should clear the Thread intrerruption if you are going to ignore it. 

I would suggest surrounding the thunk.run() with a catch of Throwable or 
Exception. In the current implementation one bad egg spoils the party 
for everyone. There is a catch of RuntimeException described as "catch 
(RuntimeException e) { // ignore exceptions from the cleanup thunk }" 
but I would suggest that this is insufficiently paranoid.

Consider a pattern like:

private static final ReferenceQueue<Object> weakListeners = new 

private static class CleanerThread extends Thread {
{ setDaemon(true); setPriority(Thread.MIN_PRIORITY); }
     public void run() {
     // Using weak ref to queue allows shutdown if class is unloaded
     WeakReference<ReferenceQueue<Object>> weakQueue = new 
     ReferenceQueue<Object> queue = null;
     while((queue = (queue == null ? weakQueue.get() : queue) != null) 
try {
       Object dead = queue.remove(10000);
       if(dead != null) {
          // do stuff with "dead"
       } else {
         queue = null; // recheck to see if queue is gone.
     } catch(InterruptedException woken) {

When 'weakListeners' is cleared when the containing class is unloaded 
then the thread will shut down after roughly 10 seconds.

I have been meaning to check whether CleanerThread needs to be in a 
separate class--an inner class, even a static one, may prevent it's 
containing class from being GCed. IDK.


More information about the core-libs-dev mailing list