Advertisement
sci4me

ReferenceBag

Jan 17th, 2019
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. package com.sci.cclj.computer.util;
  2.  
  3. import java.lang.ref.Reference;
  4. import java.lang.ref.ReferenceQueue;
  5. import java.util.HashSet;
  6. import java.util.Iterator;
  7. import java.util.Set;
  8. import java.util.function.Function;
  9.  
  10. public final class ReferenceBag<T, R extends Reference<T>> {
  11.     private final Function<T, R> constructor;
  12.     private final Set<Reference<T>> references;
  13.     private final ReferenceQueue<R> referenceQueue;
  14.  
  15.     public ReferenceBag(final Function<T, R> constructor) {
  16.         this.constructor = constructor;
  17.         this.references = new HashSet<>();
  18.         this.referenceQueue = new ReferenceQueue<>();
  19.     }
  20.  
  21.     public void add(final T obj) {
  22.         this.references.add(this.constructor.apply(obj));
  23.     }
  24.  
  25.     public T poll() {
  26.         final Iterator<Reference<T>> it = this.references.iterator();
  27.         while(it.hasNext()) {
  28.             final Reference<T> ref = it.next();
  29.             final T obj = ref.get();
  30.             if(obj != null) {
  31.                 it.remove();
  32.                 return obj;
  33.             }
  34.         }
  35.         return null;
  36.     }
  37.  
  38.     public void clean() {
  39.         for(;;) {
  40.             final Object ref = this.referenceQueue.poll();
  41.             if(ref == null) return;
  42.             this.references.remove(ref);
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement