RFR 9: 8138696 : java.lang.ref.Cleaner - an easy to use (original) (raw)
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
- Previous message: RFR: 8138716: (tz) Support tzdata2015g
- Next message: RFR 9: 8138696 : java.lang.ref.Cleaner - an easy to use > alternative to finalization (Roger Riggs)
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 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> weakQueue = new WeakReference<>(weakListeners); ReferenceQueue 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
- Previous message: RFR: 8138716: (tz) Support tzdata2015g
- Next message: RFR 9: 8138696 : java.lang.ref.Cleaner - an easy to use > alternative to finalization (Roger Riggs)
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]