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. Thread.interrupted();

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 ReferenceQueue<>();


private static class CleanerThread extends Thread {
{ setDaemon(true); setPriority(Thread.MIN_PRIORITY); }
    @Override
    @SuppressWarnings("unchecked")
    public void run() {
    // Using weak ref to queue allows shutdown if class is unloaded
WeakReference<ReferenceQueue<Object>> weakQueue = new WeakReference<>(weakListeners);
    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) {
      Thread.interrupted();
    }
  }
}

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.

Mike

Reply via email to