Java Code Examples for java.lang.ref.ReferenceQueue

The following are top voted examples for showing how to use java.lang.ref.ReferenceQueue. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: sstore-soft   File: FinalizableReferenceQueue.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Project: sstore-soft   File: MapMakerInternalMap.java   View source code 6 votes vote down vote up
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();
}
 
Example 3
Project: LearningOfThinkInJava   File: SoftRefQ.java   View source code 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,"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);
}
 
Example 4
Project: GitHub   File: Engine.java   View source code 5 votes vote down vote up
private ReferenceQueue<EngineResource<?>> getReferenceQueue() {
  if (resourceReferenceQueue == null) {
    resourceReferenceQueue = new ReferenceQueue<>();
    MessageQueue queue = Looper.myQueue();
    queue.addIdleHandler(new RefQueueIdleHandler(activeResources, resourceReferenceQueue));
  }
  return resourceReferenceQueue;
}
 
Example 5
Project: GitHub   File: ActiveResources.java   View source code 5 votes vote down vote up
@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();
}
 
Example 6
Project: openjdk-jdk10   File: DefaultStyledDocument.java   View source code 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 7
Project: openjdk-jdk10   File: ObjectStreamClass.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 8
Project: incubator-netbeans   File: PositionRef.java   View source code 5 votes vote down vote up
/** 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);
}
 
Example 9
Project: jdk8u-jdk   File: ObjectStreamClass.java   View source code 5 votes vote down vote up
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();
}
 
Example 10
Project: jdk8u-jdk   File: SubclassGC.java   View source code 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 11
Project: android-retrostreams   File: ForkJoinTask.java   View source code 5 votes vote down vote up
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);
}
 
Example 12
Project: OpenJSharp   File: WeakCache.java   View source code 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 13
Project: validator-web   File: ConcurrentReferenceHashMap.java   View source code 5 votes vote down vote up
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;
}
 
Example 14
Project: sstore-soft   File: FinalizableReferenceQueue.java   View source code 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 15
Project: ProyectoPacientes   File: NonRegisteringDriver.java   View source code 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 16
Project: openjdk-jdk10   File: WeakPairMap.java   View source code 5 votes vote down vote up
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; }
    };
}
 
Example 17
Project: openjdk-jdk10   File: SubclassGC.java   View source code 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();
        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();
        }
}
 
Example 18
Project: think-in-java   File: ReferenceTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 19
Project: lams   File: ConcurrentReferenceHashMap.java   View source code 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 20
Project: googles-monorepo-demo   File: Finalizer.java   View source code 5 votes vote down vote up
/** 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;
}
 
Example 21
Project: finmath-lib-cuda-extensions   File: RandomVariableCuda.java   View source code 5 votes vote down vote up
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;
	}
}
 
Example 22
Project: lams   File: BasicPoolEntryRef.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 23
Project: JRediClients   File: ReferenceCachedValue.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 24
Project: validator-web   File: ConcurrentReferenceHashMap.java   View source code 5 votes vote down vote up
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);
}
 
Example 25
Project: HL4A   File: SoftCachingModuleScriptProvider.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: jdk8u-jdk   File: GapContent.java   View source code 5 votes vote down vote up
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException {
    s.defaultReadObject();
    marks = new MarkVector();
    search = new MarkData(0);
    queue = new ReferenceQueue<StickyPosition>();
}
 
Example 27
Project: guava-mock   File: MapMakerInternalMap.java   View source code 5 votes vote down vote up
@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;
    }
  }
}
 
Example 28
Project: BibliotecaPS   File: NonRegisteringDriver.java   View source code 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 29
Project: guava-mock   File: Finalizer.java   View source code 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 30
Project: guava-mock   File: Finalizer.java   View source code 5 votes vote down vote up
/** 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;
}
 
Example 31
Project: guava-mock   File: MapMakerInternalMap.java   View source code 5 votes vote down vote up
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();
}
 
Example 32
Project: guava-mock   File: MapMakerInternalMap.java   View source code 5 votes vote down vote up
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;
}
 
Example 33
Project: googles-monorepo-demo   File: Finalizer.java   View source code 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 34
Project: OpenJSharp   File: DefaultStyledDocument.java   View source code 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 35
Project: jdk8u-jdk   File: LocaleResources.java   View source code 4 votes vote down vote up
ResourceReference(String cacheKey, Object o, ReferenceQueue<Object> q) {
    super(o, q);
    this.cacheKey = cacheKey;
}
 
Example 36
Project: sstable-adaptor   File: BufferPool.java   View source code 4 votes vote down vote up
public LocalPoolRef(LocalPool localPool, ReferenceQueue<? super LocalPool> q)
{
    super(localPool, q);
    chunks = localPool.chunks;
}
 
Example 37
Project: sstable-adaptor   File: Ref.java   View source code 4 votes vote down vote up
public State(final GlobalState globalState, Ref reference, ReferenceQueue<? super Ref> q)
{
    super(reference, q);
    this.globalState = globalState;
    globalState.register(this);
}
 
Example 38
Project: guava-mock   File: LocalCache.java   View source code 4 votes vote down vote up
@Override
public ValueReference<K, V> copyFor(
    ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
  return new SoftValueReference<K, V>(queue, value, entry);
}
 
Example 39
Project: s-store   File: MapMakerInternalMap.java   View source code 4 votes vote down vote up
WeakExpirableEvictableEntry(
    ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
  super(queue, key, hash, next);
}
 
Example 40
Project: s-store   File: ComputingConcurrentHashMap.java   View source code 4 votes vote down vote up
@Override
public ValueReference<K, V> copyFor(
    ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
  return this;
}