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

下面列出了怎么用java.lang.ref.ReferenceQueue的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cpsolver   文件: SoftCache.java
@Override
public void run() {
    try {
        while (true) {
            ReferenceQueue<V> q = getQueue();
            if (q == null)
                break; // soft cache deallocated -- stop the thread
            if (q.remove(10000) == null)
                continue; // was there something deallocated?
            while (q.poll() != null) {
            } // pull all the deallocated references from the queue
            cleanDeallocated(); // clean the cache
        }
        sLogger.debug("cache terminated");
    } catch (Exception e) {
        sLogger.error("cleanup thread failed, reason:" + e.getMessage(), e);
    }
}
 
源代码2 项目: codebuff   文件: LocalCache.java
Segment(
     LocalCache<K, V> map,
     int initialCapacity,
     long maxSegmentWeight,
     StatsCounter statsCounter) {
  this.map = map;
  this.maxSegmentWeight = maxSegmentWeight;
  this.statsCounter = checkNotNull(statsCounter);
  initTable(newEntryArray(initialCapacity));
  keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<K>() : null;
  valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<V>() : null;
  recencyQueue = map.usesAccessQueue()
    ? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
    : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
  writeQueue =
    map.usesWriteQueue()
      ? new WriteQueue<K, V>()
      : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
  accessQueue =
    map.usesAccessQueue()
      ? new AccessQueue<K, V>()
      : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
}
 
源代码3 项目: rdf4j   文件: ElasticsearchStore.java
public ElasticsearchStore(String hostname, int port, String clusterName, String index, boolean cacheEnabled) {
	super(cacheEnabled);
	this.hostname = hostname;
	this.port = port;
	this.clusterName = clusterName;
	this.index = index;

	clientProvider = new SingletonClientProvider(hostname, port, clusterName);

	dataStructure = new ElasticsearchDataStructure(clientProvider, index);
	namespaceStore = new ElasticsearchNamespaceStore(clientProvider, index + "_namespaces");

	ReferenceQueue<ElasticsearchStore> objectReferenceQueue = new ReferenceQueue<>();
	startGarbageCollectionMonitoring(objectReferenceQueue, new PhantomReference<>(this, objectReferenceQueue),
			clientProvider);

}
 
源代码4 项目: 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,"chenyang");
    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);
}
 
源代码5 项目: openjdk-8   文件: ClearStaleZipFileInputStreams.java
private static void runTest(int compression) throws Exception {
    ReferenceQueue<InputStream> rq = new ReferenceQueue<>();

    System.out.println("Testing with a zip file with compression level = "
            + compression);
    File f = createTestFile(compression);
    try (ZipFile zf = new ZipFile(f)) {
        Set<Object> refSet = createTransientInputStreams(zf, rq);

        System.out.println("Waiting for 'stale' input streams from ZipFile to be GC'd ...");
        System.out.println("(The test will hang on failure)");
        while (false == refSet.isEmpty()) {
            refSet.remove(rq.remove());
        }
        System.out.println("Test PASSED.");
        System.out.println();
    } finally {
        f.delete();
    }
}
 
private static ReferenceQueue<JComponent> getQueue() {
    synchronized(ActionPropertyChangeListener.class) {
        if (queue == null) {
            queue = new ReferenceQueue<JComponent>();
        }
    }
    return queue;
}
 
源代码7 项目: openjdk-8   文件: 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();
        }
}
 
源代码8 项目: netbeans   文件: ActiveQueue.java
/**
 * Gets the active reference queue.
 * @return the singleton queue
 */
public static synchronized ReferenceQueue<Object> queue() {
    if (activeReferenceQueue == null) {
        activeReferenceQueue = new Impl();
        Daemon.ping();
    }
    return activeReferenceQueue;
}
 
源代码9 项目: gemfirexd-oss   文件: ProcessorKeeper21.java
public ProcessorKeeper21(boolean useWeakRefs) {
  this.useWeakRefs = useWeakRefs;
  //should I use private construtor or this is fine
  if(useWeakRefs) {
    processorIdReferenceQueue = new ReferenceQueue();
    synchronized (cleanupAllProcessKeepers) {
      cleanupAllProcessKeepers.add(this);
    }
  } else {
    processorIdReferenceQueue = null;
  }
}
 
源代码10 项目: jdk1.8-source-analysis   文件: ProtectionDomain.java
/**
 * Removes weak keys from the map that have been enqueued
 * on the reference queue and are no longer in use.
 */
private static void processQueue(ReferenceQueue<Key> queue,
                                 ConcurrentHashMap<? extends
                                 WeakReference<Key>, ?> pdMap) {
    Reference<? extends Key> ref;
    while ((ref = queue.poll()) != null) {
        pdMap.remove(ref);
    }
}
 
源代码11 项目: openjdk-jdk8u   文件: ImageCache.java
public PixelCountSoftReference(Image referent, ReferenceQueue<? super Image> q, int pixelCount, int hash,
                               GraphicsConfiguration config, int w, int h, Object[] args) {
    super(referent, q);
    this.pixelCount = pixelCount;
    this.hash = hash;
    this.config = config;
    this.w = w;
    this.h = h;
    this.args = args;
}
 
源代码12 项目: Bytecoder   文件: ObjectStreamClass.java
FieldReflectorKey(Class<?> cl, ObjectStreamField[] fields,
                  ReferenceQueue<Class<?>> queue)
{
    super(cl, queue);
    nullClass = (cl == null);
    sigs = new String[2 * fields.length];
    for (int i = 0, j = 0; i < fields.length; i++) {
        ObjectStreamField f = fields[i];
        sigs[j++] = f.getName();
        sigs[j++] = f.getSignature();
    }
    hash = System.identityHashCode(cl) + Arrays.hashCode(sigs);
}
 
源代码13 项目: clearvolume   文件: SwitchableSoftReference.java
protected SwitchableSoftReference(	T pReferent,
									ReferenceQueue<T> pReferenceQueue,
									Runnable pCleaningRunnable)
{
	super(pReferent, pReferenceQueue);
	mHardReference = pReferent;
	mCleaningRunnable = pCleaningRunnable;
}
 
源代码14 项目: codebuff   文件: 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();
}
 
源代码15 项目: Java8CN   文件: 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);
}
 
源代码16 项目: reladomo   文件: ConcurrentDatedObjectIndex.java
public WeakEntry(Object key, ReferenceQueue queue,
      int hash, Entry next)
{
    super(key, queue);
    this.hash = hash;
    this.next = next;
}
 
private static ReferenceQueue<JComponent> getQueue() {
    synchronized(ActionPropertyChangeListener.class) {
        if (queue == null) {
            queue = new ReferenceQueue<JComponent>();
        }
    }
    return queue;
}
 
源代码18 项目: reladomo   文件: NonLruQueryIndex.java
public WeakEntry(CachedQuery key, ReferenceQueue queue,
      int hash, Entry next)
{
    super(key, queue);
    this.hash = hash;
    this.next = next;
}
 
源代码19 项目: jdk8u-dev-jdk   文件: 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);
}
 
源代码20 项目: Komondor   文件: 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
    }
}
 
源代码21 项目: openjdk-jdk8u-backup   文件: 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);
}
 
源代码22 项目: flink   文件: SafetyNetCloseableRegistry.java
PhantomDelegatingCloseableRef(
	WrappingProxyCloseable<? extends Closeable> referent,
	SafetyNetCloseableRegistry closeableRegistry,
	ReferenceQueue<? super WrappingProxyCloseable<? extends Closeable>> q) {

	super(referent, q);
	this.innerCloseable = Preconditions.checkNotNull(WrappingProxyUtil.stripProxy(referent));
	this.closeableRegistry = Preconditions.checkNotNull(closeableRegistry);
	this.debugString = referent.toString();
}
 
源代码23 项目: 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();
        }
}
 
源代码24 项目: xsync   文件: 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;
}
 
源代码25 项目: dragonwell8_jdk   文件: ImageCache.java
public PixelCountSoftReference(Image referent, ReferenceQueue<? super Image> q, int pixelCount, int hash,
                               GraphicsConfiguration config, int w, int h, Object[] args) {
    super(referent, q);
    this.pixelCount = pixelCount;
    this.hash = hash;
    this.config = config;
    this.w = w;
    this.h = h;
    this.args = args;
}
 
源代码26 项目: reladomo   文件: NonLruQueryIndex.java
@Override
public Entry cloneWithNext(ReferenceQueue queue, Entry next)
{
    if (this.next == next)
    {
        return this;
    }
    return new WeakEntry(this.get(), queue, this.hash, next);
}
 
源代码27 项目: validator-web   文件: 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;
}
 
源代码28 项目: openjdk-jdk9   文件: ImageCache.java
public PixelCountSoftReference(Image referent, ReferenceQueue<? super Image> q, int pixelCount, int hash,
                               GraphicsConfiguration config, int w, int h, Object[] args) {
    super(referent, q);
    this.pixelCount = pixelCount;
    this.hash = hash;
    this.config = config;
    this.w = w;
    this.h = h;
    this.args = args;
}
 
源代码29 项目: xsync   文件: ConcurrentReferenceHashMap.java
WeakValueReference(V value, Object keyRef, int hash, ReferenceQueue<Object> refQueue) {
	super(value, refQueue);
	this.keyRef = keyRef;
	this.hash = hash;
}
 
源代码30 项目: netbeans   文件: AbstractLookup.java
private static ReferenceQueue<Object> activeQueue() {
    return ActiveQueue.queue();
}