java.lang.ref.ReferenceQueue Java Examples

The following examples show how to use java.lang.ref.ReferenceQueue. 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 File: ElasticsearchStore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #2
Source File: ClearStaleZipFileInputStreams.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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 #3
Source File: SoftRefQ.java    From LearningOfThinkInJava with 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 #4
Source File: LocalCache.java    From codebuff with 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 #5
Source File: SoftCache.java    From cpsolver with 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 #6
Source File: SwitchableSoftReference.java    From clearvolume with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected SwitchableSoftReference(	T pReferent,
									ReferenceQueue<T> pReferenceQueue,
									Runnable pCleaningRunnable)
{
	super(pReferent, pReferenceQueue);
	mHardReference = pReferent;
	mCleaningRunnable = pCleaningRunnable;
}
 
Example #7
Source File: ProtectionDomain.java    From jdk1.8-source-analysis with 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 #8
Source File: ProcessorKeeper21.java    From gemfirexd-oss with 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 #9
Source File: ConcurrentReferenceHashMap.java    From validator-web with 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 #10
Source File: ImageCache.java    From openjdk-jdk9 with 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 #11
Source File: ActiveQueue.java    From netbeans with 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 #12
Source File: SubclassGC.java    From openjdk-8 with 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 #13
Source File: ActionPropertyChangeListener.java    From JDKSourceCode1.8 with 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 #14
Source File: NonLruQueryIndex.java    From reladomo with 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 #15
Source File: ImageCache.java    From dragonwell8_jdk with 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 #16
Source File: ConcurrentReferenceHashMap.java    From xsync with 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 #17
Source File: ObjectStreamClass.java    From Bytecoder with 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 #18
Source File: ImageCache.java    From openjdk-jdk8u with 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 #19
Source File: Finalizer.java    From codebuff with 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 #20
Source File: SubclassGC.java    From jdk8u-jdk with 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 #21
Source File: SafetyNetCloseableRegistry.java    From flink with 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 #22
Source File: WeakCache.java    From Java8CN with 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 #23
Source File: ConcurrentDatedObjectIndex.java    From reladomo with 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 #24
Source File: ActionPropertyChangeListener.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static ReferenceQueue<JComponent> getQueue() {
    synchronized(ActionPropertyChangeListener.class) {
        if (queue == null) {
            queue = new ReferenceQueue<JComponent>();
        }
    }
    return queue;
}
 
Example #25
Source File: NonLruQueryIndex.java    From reladomo with 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 #26
Source File: DefaultStyledDocument.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #27
Source File: NonRegisteringDriver.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
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 #28
Source File: WeakCache.java    From openjdk-jdk8u-backup with GNU General Public License v2.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 #29
Source File: DGCImplInsulation.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        TestLibrary.suggestSecurityManager(null);

        Permissions perms = new Permissions();
        perms.add(new SocketPermission("*:1024-", "listen"));
        AccessControlContext acc =
            new AccessControlContext(new ProtectionDomain[] {
                new ProtectionDomain(
                    new CodeSource(null, (Certificate[]) null), perms) });

        Remote impl = new DGCImplInsulation();;

        try {
            Remote stub = (Remote) java.security.AccessController.doPrivileged(
                new ExportAction(impl));
            System.err.println("exported remote object; local stub: " + stub);

            MarshalledObject mobj = new MarshalledObject(stub);
            stub = (Remote) mobj.get();
            System.err.println("marshalled/unmarshalled stub: " + stub);

            ReferenceQueue refQueue = new ReferenceQueue();
            Reference weakRef = new WeakReference(impl, refQueue);
            impl = null;
            System.gc();
            if (refQueue.remove(TIMEOUT) == weakRef) {
                throw new RuntimeException(
                    "TEST FAILED: remote object garbage collected");
            } else {
                System.err.println("TEST PASSED");
                stub = null;
                System.gc();
                Thread.sleep(2000);
                System.gc();
            }
        } finally {
            try {
                UnicastRemoteObject.unexportObject(impl, true);
            } catch (Exception e) {
            }
        }
    }
 
Example #30
Source File: XulTaskCollector.java    From starcor.xul with GNU Lesser General Public License v3.0 4 votes vote down vote up
public XulVolatileReference(T r, ReferenceQueue<? super T> q) {
	super(r, q);
}