bestsss

ReferenceQueue expunge

Sep 2nd, 2014
18
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.lang.ref.*;
  2.  
  3. public class Expunger{
  4.   public static interface Cleaner<T, Ref extends Reference<? extends T>>{
  5.     void clean(Ref ref);
  6.   }
  7.  
  8.   public static <T, Ref extends Reference<? extends T>> void expunge(Cleaner<T, Ref> cleaner, final ReferenceQueue<T> queue, int expungeThreshold){
  9.     Reference<? extends T> w=queue.poll();
  10.     if (w==null)
  11.       return;//keep the method short, so it's inlined; queue being empty is the fast lane
  12.    
  13.     expungeImpl(cleaner, w, queue, expungeThreshold);  
  14.   }
  15.  
  16.   static <T, Ref extends Reference<? extends T>> void expungeImpl(final Cleaner<T, Ref> cleaner, Reference<? extends T> ref, final ReferenceQueue<T> queue, int expungeThreshold){
  17.     expunge(cleaner, ref);
  18.     for (;--expungeThreshold>0  && null!=(ref=queue.poll());){
  19.       expunge(cleaner, ref);
  20.     }
  21.     if (expungeThreshold==0){//delegate a full expunge to the finalizer
  22.       //the anon. class stores cleaner and queue in fields, and the c-tor has happens before with finalize() unlike any other method...
  23.       new Object(){//feel free to extend WeakRefence(cleaner) and also keep weak ref to queue useful for non-native resources
  24.         protected void finalize(){//keep in mind: the execution of cleaner.clean(Ref) will not have the right ContextClassLoader, ThreadGroup, AccessControlContext
  25.           expunge(cleaner, queue, Integer.MAX_VALUE);
  26.         }
  27.       };
  28.     }
  29.   }
  30.  
  31.   @SuppressWarnings("unchecked")
  32.   private static <T, Ref extends Reference<? extends T>> void expunge(Cleaner<T, Ref> cleaner, Reference<? extends T> ref){
  33.     cleaner.clean((Ref) ref);
  34.   }
  35. }
RAW Paste Data