Java Code Examples for java.lang.ref.ReferenceQueue

The following examples show how to use java.lang.ref.ReferenceQueue. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cpsolver   Source File: SoftCache.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example 2
Source Project: codebuff   Source File: LocalCache.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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();
}
 
Example 3
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);

}
 
Example 4
Source Project: LearningOfThinkInJava   Source File: SoftRefQ.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 5
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();
    }
}
 
Example 6
Source Project: JDKSourceCode1.8   Source File: ActionPropertyChangeListener.java    License: MIT License 5 votes vote down vote up
private static ReferenceQueue<JComponent> getQueue() {
    synchronized(ActionPropertyChangeListener.class) {
        if (queue == null) {
            queue = new ReferenceQueue<JComponent>();
        }
    }
    return queue;
}
 
Example 7
Source Project: openjdk-8   Source File: SubclassGC.java    License: GNU General Public License v2.0 5 votes vote down vote up
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();
        }
}
 
Example 8
Source Project: netbeans   Source File: ActiveQueue.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source Project: gemfirexd-oss   Source File: ProcessorKeeper21.java    License: Apache License 2.0 5 votes vote down vote up
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;
  }
}
 
Example 10
Source Project: jdk1.8-source-analysis   Source File: ProtectionDomain.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 11
Source Project: openjdk-jdk8u   Source File: ImageCache.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 12
Source Project: Bytecoder   Source File: ObjectStreamClass.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 13
protected SwitchableSoftReference(	T pReferent,
									ReferenceQueue<T> pReferenceQueue,
									Runnable pCleaningRunnable)
{
	super(pReferent, pReferenceQueue);
	mHardReference = pReferent;
	mCleaningRunnable = pCleaningRunnable;
}
 
Example 14
Source Project: codebuff   Source File: Finalizer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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();
}
 
Example 15
Source Project: Java8CN   Source File: WeakCache.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 16
Source Project: reladomo   Source File: ConcurrentDatedObjectIndex.java    License: Apache License 2.0 5 votes vote down vote up
public WeakEntry(Object key, ReferenceQueue queue,
      int hash, Entry next)
{
    super(key, queue);
    this.hash = hash;
    this.next = next;
}
 
Example 17
private static ReferenceQueue<JComponent> getQueue() {
    synchronized(ActionPropertyChangeListener.class) {
        if (queue == null) {
            queue = new ReferenceQueue<JComponent>();
        }
    }
    return queue;
}
 
Example 18
Source Project: reladomo   Source File: NonLruQueryIndex.java    License: Apache License 2.0 5 votes vote down vote up
public WeakEntry(CachedQuery key, ReferenceQueue queue,
      int hash, Entry next)
{
    super(key, queue);
    this.hash = hash;
    this.next = next;
}
 
Example 19
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);
}
 
Example 20
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
    }
}
 
Example 21
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);
}
 
Example 22
Source Project: flink   Source File: SafetyNetCloseableRegistry.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 23
Source Project: jdk8u-jdk   Source File: SubclassGC.java    License: GNU General Public License v2.0 5 votes vote down vote up
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();
        }
}
 
Example 24
Source Project: xsync   Source File: ConcurrentReferenceHashMap.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 25
Source Project: dragonwell8_jdk   Source File: ImageCache.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 26
Source Project: reladomo   Source File: NonLruQueryIndex.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Entry cloneWithNext(ReferenceQueue queue, Entry next)
{
    if (this.next == next)
    {
        return this;
    }
    return new WeakEntry(this.get(), queue, this.hash, next);
}
 
Example 27
Source Project: validator-web   Source File: ConcurrentReferenceHashMap.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 28
Source Project: openjdk-jdk9   Source File: ImageCache.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 29
Source Project: xsync   Source File: ConcurrentReferenceHashMap.java    License: Apache License 2.0 4 votes vote down vote up
WeakValueReference(V value, Object keyRef, int hash, ReferenceQueue<Object> refQueue) {
	super(value, refQueue);
	this.keyRef = keyRef;
	this.hash = hash;
}
 
Example 30
Source Project: netbeans   Source File: AbstractLookup.java    License: Apache License 2.0 4 votes vote down vote up
private static ReferenceQueue<Object> activeQueue() {
    return ActiveQueue.queue();
}