Java 类java.lang.ref.ReferenceQueue 实例源码

项目:sstore-soft    文件:FinalizableReferenceQueue.java   
/**
 * Constructs a new queue.
 */
public FinalizableReferenceQueue() {
  // We could start the finalizer lazily, but I'd rather it blow up early.
  queue = new ReferenceQueue<Object>();
  frqRef = new PhantomReference<Object>(this, queue);
  boolean threadStarted = false;
  try {
    startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef);
    threadStarted = true;
  } catch (IllegalAccessException impossible) {
    throw new AssertionError(impossible); // startFinalizer() is public
  } catch (Throwable t) {
    logger.log(Level.INFO, "Failed to start reference finalizer thread."
        + " Reference cleanup will only occur when new references are created.", t);
  }

  this.threadStarted = threadStarted;
}
项目:sstore-soft    文件:MapMakerInternalMap.java   
Segment(MapMakerInternalMap<K, V> map, int initialCapacity, int maxSegmentSize) {
  this.map = map;
  this.maxSegmentSize = maxSegmentSize;
  initTable(newEntryArray(initialCapacity));

  keyReferenceQueue = map.usesKeyReferences()
       ? new ReferenceQueue<K>() : null;

  valueReferenceQueue = map.usesValueReferences()
       ? new ReferenceQueue<V>() : null;

  recencyQueue = (map.evictsBySize() || map.expiresAfterAccess())
      ? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
      : MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();

  evictionQueue = map.evictsBySize()
      ? new EvictionQueue<K, V>()
      : MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();

  expirationQueue = map.expires()
      ? new ExpirationQueue<K, V>()
      : MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();
}
项目:LearningOfThinkInJava    文件:SoftRefQ.java   
public static void main(String[] args) throws InterruptedException{
    Thread t=new CheckRefQueue();
    t.setDaemon(true);
    t.start();
    User u=new User(1,"geym");
    softQueue=new ReferenceQueue<User>();
    UserSoftReference userSoftRef=new UserSoftReference(u,softQueue);

    u=null;
    System.out.println(userSoftRef.get());
    System.gc();

    System.out.println("After GC:");
    System.out.println(userSoftRef.get());

    System.out.println("try to create byte array and GC");

    byte[] b=new byte[1024*925*7];
    System.gc();
    System.out.println(userSoftRef.get());

    Thread.sleep(1000);
}
项目:GitHub    文件:Engine.java   
private ReferenceQueue<EngineResource<?>> getReferenceQueue() {
  if (resourceReferenceQueue == null) {
    resourceReferenceQueue = new ReferenceQueue<>();
    MessageQueue queue = Looper.myQueue();
    queue.addIdleHandler(new RefQueueIdleHandler(activeResources, resourceReferenceQueue));
  }
  return resourceReferenceQueue;
}
项目:GitHub    文件:ActiveResources.java   
@Synthetic
@SuppressWarnings("WeakerAccess")
ResourceWeakReference(
    Key key, EngineResource<?> r, ReferenceQueue<? super EngineResource<?>> q) {
  super(r, q);
  this.key = Preconditions.checkNotNull(key);
  this.resource = Preconditions.checkNotNull(r.getResource());
  isCacheable = r.isCacheable();
}
项目:openjdk-jdk10    文件:DefaultStyledDocument.java   
AbstractChangeHandler(DefaultStyledDocument d) {
    Class<?> c = getClass();
    ReferenceQueue<DefaultStyledDocument> q;
    synchronized (queueMap) {
        q = queueMap.get(c);
        if (q == null) {
            q = new ReferenceQueue<DefaultStyledDocument>();
            queueMap.put(c, q);
        }
    }
    doc = new DocReference(d, q);
}
项目:openjdk-jdk10    文件:ObjectStreamClass.java   
/**
 * Removes from the specified map any keys that have been enqueued
 * on the specified reference queue.
 */
static void processQueue(ReferenceQueue<Class<?>> queue,
                         ConcurrentMap<? extends
                         WeakReference<Class<?>>, ?> map)
{
    Reference<? extends Class<?>> ref;
    while((ref = queue.poll()) != null) {
        map.remove(ref);
    }
}
项目:incubator-netbeans    文件:PositionRef.java   
/** Initialize the variables to the default values. */
protected void init() {
    queue = new ReferenceQueue<PositionRef>();

    // A stable mark used to simplify operations with the list
    head = new ChainItem(null, queue, null);
}
项目:jdk8u-jdk    文件:ObjectStreamClass.java   
FieldReflectorKey(Class<?> cl, ObjectStreamField[] fields,
                  ReferenceQueue<Class<?>> queue)
{
    super(cl, queue);
    nullClass = (cl == null);
    StringBuilder sbuf = new StringBuilder();
    for (int i = 0; i < fields.length; i++) {
        ObjectStreamField f = fields[i];
        sbuf.append(f.getName()).append(f.getSignature());
    }
    sigs = sbuf.toString();
    hash = System.identityHashCode(cl) + sigs.hashCode();
}
项目:jdk8u-jdk    文件:SubclassGC.java   
public static final void main(String[] args) throws Exception {
        System.err.println("\n Regression test for bug 6232010\n");
        if (System.getSecurityManager() == null) {
                System.setSecurityManager(new SecurityManager());
        }

        ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
        ClassLoader loader = new URLClassLoader(((URLClassLoader) systemLoader).getURLs(),
                                                                                systemLoader.getParent());
        Class<? extends ObjectOutputStream> cl =
                Class.forName(SubclassOfOOS.class.getName(), false,
                                          loader).asSubclass(ObjectOutputStream.class);

        Constructor<? extends ObjectOutputStream> cons =
                cl.getConstructor(OutputStream.class);

        OutputStream os = new ByteArrayOutputStream();
        ObjectOutputStream obj = cons.newInstance(os);

        final ReferenceQueue<Class<?>> queue = new ReferenceQueue<Class<?>>();
        WeakReference<Class<?>> ref = new WeakReference<Class<?>>(cl, queue);

        cl = null;
        obj = null;
        loader = null;
        cons = null;
        systemLoader = null;

        System.err.println("\nStart Garbage Collection right now");
        System.gc();

        Reference<? extends Class<?>> dequeued = queue.remove(TIMEOUT);
        if (dequeued == ref) {
                System.err.println("\nTEST PASSED");
        } else {
                throw new Error();
        }
}
项目:android-retrostreams    文件:ForkJoinTask.java   
ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next,
              ReferenceQueue<ForkJoinTask<?>> exceptionTableRefQueue) {
    super(task, exceptionTableRefQueue);
    this.ex = ex;
    this.next = next;
    this.thrower = Thread.currentThread().getId();
    this.hashCode = System.identityHashCode(task);
}
项目:OpenJSharp    文件:WeakCache.java   
static <K> Object valueOf(K key, ReferenceQueue<K> refQueue) {
    return key == null
           // null key means we can't weakly reference it,
           // so we use a NULL_KEY singleton as cache key
           ? NULL_KEY
           // non-null key requires wrapping with a WeakReference
           : new CacheKey<>(key, refQueue);
}
项目:validator-web    文件:ConcurrentReferenceHashMap.java   
final Object newValueReference(V value, ReferenceType valueType,
                               ReferenceQueue<Object> refQueue) {
    if (valueType == ReferenceType.WEAK)
        return new WeakValueReference<V>(value, keyRef, hash, refQueue);
    if (valueType == ReferenceType.SOFT)
        return new SoftValueReference<V>(value, keyRef, hash, refQueue);

    return value;
}
项目:sstore-soft    文件:FinalizableReferenceQueue.java   
/**
 * Looks up Finalizer.startFinalizer().
 */
static Method getStartFinalizer(Class<?> finalizer) {
  try {
    return finalizer.getMethod(
        "startFinalizer",
        Class.class,
        ReferenceQueue.class,
        PhantomReference.class);
  } catch (NoSuchMethodException e) {
    throw new AssertionError(e);
  }
}
项目:ProyectoPacientes    文件:NonRegisteringDriver.java   
ConnectionPhantomReference(ConnectionImpl connectionImpl, ReferenceQueue<ConnectionImpl> q) {
    super(connectionImpl, q);

    try {
        this.io = connectionImpl.getIO().getNetworkResources();
    } catch (SQLException e) {
        // if we somehow got here and there's really no i/o, we deal with it later
    }
}
项目:openjdk-jdk10    文件:WeakPairMap.java   
Weak(K1 k1, K2 k2, ReferenceQueue<Object> queue) {
    super(k1, queue);
    hash = Pair.hashCode(k1, k2);
    peer = new WeakRefPeer<>(k2, queue) {
        // link back to <K1> peer
        @Override
        Weak<?, ?> weakPair() { return Weak.this; }
    };
}
项目:openjdk-jdk10    文件:SubclassGC.java   
public static final void main(String[] args) throws Exception {
        System.err.println("\n Regression test for bug 6232010\n");
        if (System.getSecurityManager() == null) {
                System.setSecurityManager(new SecurityManager());
        }

        ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
        URL testClassesURL = new File(System.getProperty("test.classes")).toURI().toURL();
        ClassLoader loader = new URLClassLoader(new URL[] { testClassesURL } ,
                                                systemLoader.getParent());
        Class<? extends ObjectOutputStream> cl =
                Class.forName(SubclassOfOOS.class.getName(), false,
                                          loader).asSubclass(ObjectOutputStream.class);

        Constructor<? extends ObjectOutputStream> cons =
                cl.getConstructor(OutputStream.class);

        OutputStream os = new ByteArrayOutputStream();
        ObjectOutputStream obj = cons.newInstance(os);

        final ReferenceQueue<Class<?>> queue = new ReferenceQueue<Class<?>>();
        WeakReference<Class<?>> ref = new WeakReference<Class<?>>(cl, queue);

        cl = null;
        obj = null;
        loader = null;
        cons = null;
        systemLoader = null;

        System.err.println("\nStart Garbage Collection right now");
        System.gc();

        Reference<? extends Class<?>> dequeued = queue.remove(TIMEOUT);
        if (dequeued == ref) {
                System.err.println("\nTEST PASSED");
        } else {
                throw new Error();
        }
}
项目:think-in-java    文件:ReferenceTest.java   
public static void main(String[] args) {
    //使用软引用构建敏感数据的缓存
    String str = new String("Hello");
    ReferenceQueue queue = new ReferenceQueue();
    SoftReference<String> softReferenceString = new SoftReference<>(str,queue);
    str = null;
    System.gc();
    System.out.println(softReferenceString.get());

    WeakReference<String> weakReferenceString = new WeakReference<>(new String("World"));
    System.out.println(weakReferenceString.get());

    WeakHashMap weakHashMap = new WeakHashMap();
    weakHashMap.put(1,2);
}
项目:lams    文件:ConcurrentReferenceHashMap.java   
final Object newKeyReference(K key, ReferenceType keyType,
                             ReferenceQueue<Object> refQueue) {
    if ( keyType == ReferenceType.WEAK ) {
        return new WeakKeyReference<K>( key, hash, refQueue );
    }
    if ( keyType == ReferenceType.SOFT ) {
        return new SoftKeyReference<K>( key, hash, refQueue );
    }

    return key;
}
项目:googles-monorepo-demo    文件:Finalizer.java   
/** Constructs a new finalizer thread. */
private Finalizer(
    Class<?> finalizableReferenceClass,
    ReferenceQueue<Object> queue,
    PhantomReference<Object> frqReference) {
  this.queue = queue;

  this.finalizableReferenceClassReference =
      new WeakReference<Class<?>>(finalizableReferenceClass);

  // Keep track of the FRQ that started us so we know when to stop.
  this.frqReference = frqReference;
}
项目:finmath-lib-cuda-extensions    文件:RandomVariableCuda.java   
private CUdeviceptr createCUdeviceptr(long size) {
    synchronized (vectorsInUseReferenceMap) {
        CUdeviceptr cuDevicePtr = getCUdeviceptr(size);

        // Manage CUdeviceptr
        ReferenceQueue<RandomVariableCuda> vectorsToRecycleReferenceQueue = vectorsToRecycleReferenceQueueMap.get(new Integer((int)size));
        WeakReference<RandomVariableCuda> reference = new WeakReference<RandomVariableCuda>(this, vectorsToRecycleReferenceQueue);
        vectorsInUseReferenceMap.put(reference, cuDevicePtr);

        return cuDevicePtr;
    }
}
项目:lams    文件:BasicPoolEntryRef.java   
/**
 * Creates a new reference to a pool entry.
 *
 * @param entry   the pool entry, must not be <code>null</code>
 * @param queue   the reference queue, or <code>null</code>
 */
public BasicPoolEntryRef(BasicPoolEntry entry,
                         ReferenceQueue<Object> queue) {
    super(entry, queue);
    if (entry == null) {
        throw new IllegalArgumentException
            ("Pool entry must not be null.");
    }
    route = entry.getPlannedRoute();
}
项目:JRediClients    文件:ReferenceCachedValue.java   
public ReferenceCachedValue(K key, V value, long ttl, long maxIdleTime, ReferenceQueue<V> queue, Type type) {
    super(key, null, ttl, maxIdleTime);
    if (type == Type.SOFT) {
        this.ref = new CachedValueSoftReference<V>(this, value, queue);
    } else {
        this.ref = new CachedValueWeakReference<V>(this, value, queue);
    }
}
项目:validator-web    文件:ConcurrentReferenceHashMap.java   
HashEntry(K key, int hash, HashEntry<K, V> next, V value,
          ReferenceType keyType, ReferenceType valueType,
          ReferenceQueue<Object> refQueue) {
    this.hash = hash;
    this.next = next;
    this.keyRef = newKeyReference(key, keyType, refQueue);
    this.valueRef = newValueReference(value, valueType, refQueue);
}
项目:HL4A    文件:SoftCachingModuleScriptProvider.java   
ScriptReference(Script script, String moduleId, URI uri, URI base,
        Object validator, ReferenceQueue<Script> refQueue) {
    super(script, refQueue);
    this.moduleId = moduleId;
    this.uri = uri;
    this.base = base;
    this.validator = validator;
}
项目:jdk8u-jdk    文件:GapContent.java   
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException {
    s.defaultReadObject();
    marks = new MarkVector();
    search = new MarkData(0);
    queue = new ReferenceQueue<StickyPosition>();
}
项目:guava-mock    文件:MapMakerInternalMap.java   
@GuardedBy("this")
void drainValueReferenceQueue(ReferenceQueue<V> valueReferenceQueue) {
  Reference<? extends V> ref;
  int i = 0;
  while ((ref = valueReferenceQueue.poll()) != null) {
    @SuppressWarnings("unchecked")
    WeakValueReference<K, V, E> valueReference = (WeakValueReference<K, V, E>) ref;
    map.reclaimValue(valueReference);
    if (++i == DRAIN_MAX) {
      break;
    }
  }
}
项目:BibliotecaPS    文件:NonRegisteringDriver.java   
ConnectionPhantomReference(ConnectionImpl connectionImpl, ReferenceQueue<ConnectionImpl> q) {
    super(connectionImpl, q);

    try {
        this.io = connectionImpl.getIO().getNetworkResources();
    } catch (SQLException e) {
        // if we somehow got here and there's really no i/o, we deal with it later
    }
}
项目:guava-mock    文件:Finalizer.java   
/**
 * Starts the Finalizer thread. FinalizableReferenceQueue calls this method reflectively.
 *
 * @param finalizableReferenceClass FinalizableReference.class.
 * @param queue a reference queue that the thread will poll.
 * @param frqReference a phantom reference to the FinalizableReferenceQueue, which will be queued
 *     either when the FinalizableReferenceQueue is no longer referenced anywhere, or when its
 *     close() method is called.
 */
public static void startFinalizer(
    Class<?> finalizableReferenceClass,
    ReferenceQueue<Object> queue,
    PhantomReference<Object> frqReference) {
  /*
   * We use FinalizableReference.class for two things:
   *
   * 1) To invoke FinalizableReference.finalizeReferent()
   *
   * 2) To detect when FinalizableReference's class loader has to be garbage collected, at which
   * point, Finalizer can stop running
   */
  if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) {
    throw new IllegalArgumentException("Expected " + FINALIZABLE_REFERENCE + ".");
  }

  Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference);
  Thread thread = new Thread(finalizer);
  thread.setName(Finalizer.class.getName());
  thread.setDaemon(true);

  try {
    if (inheritableThreadLocals != null) {
      inheritableThreadLocals.set(thread, null);
    }
  } catch (Throwable t) {
    logger.log(
        Level.INFO,
        "Failed to clear thread local values inherited by reference finalizer thread.",
        t);
  }

  thread.start();
}
项目:guava-mock    文件:Finalizer.java   
/** Constructs a new finalizer thread. */
private Finalizer(
    Class<?> finalizableReferenceClass,
    ReferenceQueue<Object> queue,
    PhantomReference<Object> frqReference) {
  this.queue = queue;

  this.finalizableReferenceClassReference =
      new WeakReference<Class<?>>(finalizableReferenceClass);

  // Keep track of the FRQ that started us so we know when to stop.
  this.frqReference = frqReference;
}
项目:guava-mock    文件:MapMakerInternalMap.java   
void setValue(V value, ReferenceQueue<V> queueForValues) {
  WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> previous = this.valueReference;
  this.valueReference =
      new WeakValueReferenceImpl<K, V, StrongKeyWeakValueEntry<K, V>>(
          queueForValues, value, this);
  previous.clear();
}
项目:guava-mock    文件:MapMakerInternalMap.java   
WeakKeyStrongValueEntry<K, V> copy(
    ReferenceQueue<K> queueForKeys, WeakKeyStrongValueEntry<K, V> newNext) {
  WeakKeyStrongValueEntry<K, V> newEntry =
      new WeakKeyStrongValueEntry<K, V>(queueForKeys, getKey(), this.hash, newNext);
  newEntry.setValue(value);
  return newEntry;
}
项目:googles-monorepo-demo    文件:Finalizer.java   
/**
 * Starts the Finalizer thread. FinalizableReferenceQueue calls this method reflectively.
 *
 * @param finalizableReferenceClass FinalizableReference.class.
 * @param queue a reference queue that the thread will poll.
 * @param frqReference a phantom reference to the FinalizableReferenceQueue, which will be queued
 *     either when the FinalizableReferenceQueue is no longer referenced anywhere, or when its
 *     close() method is called.
 */
public static void startFinalizer(
    Class<?> finalizableReferenceClass,
    ReferenceQueue<Object> queue,
    PhantomReference<Object> frqReference) {
  /*
   * We use FinalizableReference.class for two things:
   *
   * 1) To invoke FinalizableReference.finalizeReferent()
   *
   * 2) To detect when FinalizableReference's class loader has to be garbage collected, at which
   * point, Finalizer can stop running
   */
  if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) {
    throw new IllegalArgumentException("Expected " + FINALIZABLE_REFERENCE + ".");
  }

  Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference);
  Thread thread = new Thread(finalizer);
  thread.setName(Finalizer.class.getName());
  thread.setDaemon(true);

  try {
    if (inheritableThreadLocals != null) {
      inheritableThreadLocals.set(thread, null);
    }
  } catch (Throwable t) {
    logger.log(
        Level.INFO,
        "Failed to clear thread local values inherited by reference finalizer thread.",
        t);
  }

  thread.start();
}
项目:OpenJSharp    文件:DefaultStyledDocument.java   
AbstractChangeHandler(DefaultStyledDocument d) {
    Class c = getClass();
    ReferenceQueue<DefaultStyledDocument> q;
    synchronized (queueMap) {
        q = queueMap.get(c);
        if (q == null) {
            q = new ReferenceQueue<DefaultStyledDocument>();
            queueMap.put(c, q);
        }
    }
    doc = new DocReference(d, q);
}
项目:jdk8u-jdk    文件:LocaleResources.java   
ResourceReference(String cacheKey, Object o, ReferenceQueue<Object> q) {
    super(o, q);
    this.cacheKey = cacheKey;
}
项目:sstable-adaptor    文件:BufferPool.java   
public LocalPoolRef(LocalPool localPool, ReferenceQueue<? super LocalPool> q)
{
    super(localPool, q);
    chunks = localPool.chunks;
}
项目:sstable-adaptor    文件:Ref.java   
public State(final GlobalState globalState, Ref reference, ReferenceQueue<? super Ref> q)
{
    super(reference, q);
    this.globalState = globalState;
    globalState.register(this);
}
项目:guava-mock    文件:LocalCache.java   
@Override
public ValueReference<K, V> copyFor(
    ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
  return new SoftValueReference<K, V>(queue, value, entry);
}
项目:s-store    文件:MapMakerInternalMap.java   
WeakExpirableEvictableEntry(
    ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
  super(queue, key, hash, next);
}
项目:s-store    文件:ComputingConcurrentHashMap.java   
@Override
public ValueReference<K, V> copyFor(
    ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
  return this;
}