Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.ref.*;
- public class Expunger{
- public static interface Cleaner<T, Ref extends Reference<? extends T>>{
- void clean(Ref ref);
- }
- public static <T, Ref extends Reference<? extends T>> void expunge(Cleaner<T, Ref> cleaner, final ReferenceQueue<T> queue, int expungeThreshold){
- Reference<? extends T> w=queue.poll();
- if (w==null)
- return;//keep the method short, so it's inlined; queue being empty is the fast lane
- expungeImpl(cleaner, w, queue, expungeThreshold);
- }
- static <T, Ref extends Reference<? extends T>> void expungeImpl(final Cleaner<T, Ref> cleaner, Reference<? extends T> ref, final ReferenceQueue<T> queue, int expungeThreshold){
- expunge(cleaner, ref);
- for (;--expungeThreshold>0 && null!=(ref=queue.poll());){
- expunge(cleaner, ref);
- }
- if (expungeThreshold==0){//delegate a full expunge to the finalizer
- //the anon. class stores cleaner and queue in fields, and the c-tor has happens before with finalize() unlike any other method...
- new Object(){//feel free to extend WeakRefence(cleaner) and also keep weak ref to queue useful for non-native resources
- protected void finalize(){//keep in mind: the execution of cleaner.clean(Ref) will not have the right ContextClassLoader, ThreadGroup, AccessControlContext
- expunge(cleaner, queue, Integer.MAX_VALUE);
- }
- };
- }
- }
- @SuppressWarnings("unchecked")
- private static <T, Ref extends Reference<? extends T>> void expunge(Cleaner<T, Ref> cleaner, Reference<? extends T> ref){
- cleaner.clean((Ref) ref);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment