java.lang.ref.Reference类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(165)

本文整理了Java中java.lang.ref.Reference类的一些代码示例,展示了Reference类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Reference类的具体详情如下:
包路径:java.lang.ref.Reference
类名称:Reference

Reference介绍

[英]Provides an abstract class which describes behavior common to all reference objects. It is not possible to create immediate subclasses of Reference in addition to the ones provided by this package. It is also not desirable to do so, since references require very close cooperation with the system's garbage collector. The existing, specialized reference classes should be used instead.

Three different type of references exist, each being weaker than the preceding one: java.lang.ref.SoftReference, java.lang.ref.WeakReference, and java.lang.ref.PhantomReference. "Weakness" here means that less restrictions are being imposed on the garbage collector as to when it is allowed to actually garbage-collect the referenced object.

In order to use reference objects properly it is important to understand the different types of reachability that trigger their clearing and enqueueing. The following table lists these, from strongest to weakest. For each row, an object is said to have the reachability on the left side if (and only if) it fulfills all of the requirements on the right side. In all rows, consider the root set to be a set of references that are "resistant" to garbage collection (that is, running threads, method parameters, local variables, static fields and the like).

Strongly reachable

  • There exists at least one path from the root set to the object that does not traverse any instance of a java.lang.ref.Reference subclass.
    Softly reachable
  • The object is not strongly reachable.
  • There exists at least one path from the root set to the object that does traverse a java.lang.ref.SoftReference instance, but no java.lang.ref.WeakReferenceor java.lang.ref.PhantomReference instances.
    Weakly reachable
  • The object is neither strongly nor softly reachable.
  • There exists at least one path from the root set to the object that does traverse a java.lang.ref.WeakReference instance, but no java.lang.ref.PhantomReferenceinstances.
    Phantom-reachable
  • The object is neither strongly, softly, nor weakly reachable.
  • The object is referenced by a java.lang.ref.PhantomReference instance.
  • The object has already been finalized.
    [中]提供一个抽象类,该类描述所有引用对象的通用行为。除了这个包提供的子类之外,不可能创建引用的直接子类。这样做也是不可取的,因为引用需要与系统的垃圾收集器密切合作。应该使用现有的专用引用类。
    存在三种不同类型的引用,每种都比前一种弱:java。lang.ref.SoftReference,java。lang.ref.WeakReference和java。lang.ref.PhantomReference。这里的“弱点”意味着垃圾收集器在何时被允许对引用的对象进行垃圾收集时受到的限制更少。
    为了正确使用引用对象,了解触发其清除和排队的不同可达性类型很重要。下表从最强到最弱列出了这些。对于每一行,当(且仅当)一个对象满足右侧的所有要求时,称其在左侧具有可达性。在所有行中,将根集视为一组对垃圾收集(即运行线程、方法参数、局部变量、静态字段等)“抵抗”的引用。
    强可达
    *从根集合到不遍历任何java实例的对象至少存在一条路径。lang.ref.Reference子类。
    轻触
    *该对象的可达性不强。
    *从根集到确实遍历java的对象至少存在一条路径。lang.ref.SoftReference实例,但没有java。lang.ref.WeakReferenceor java。lang.ref.PhantomReference实例。
    弱可达
    *这个物体既不牢固也不柔软。
    *从根集到确实遍历java的对象至少存在一条路径。lang.ref.WeakReference实例,但没有java。lang.ref.PhantomReferenceinstances。
    幻影可达
    *这个物体既不强,也不软,也不弱可及。
    *该对象由java语言引用。lang.ref.PhantomReference实例。
    *目标已经确定。

代码示例

代码示例来源:origin: netty/netty

private V unfold(Reference<V> ref) {
  if (ref == null) {
    return null;
  }
  return ref.get();
}

代码示例来源:origin: commons-collections/commons-collections

boolean purge(Reference ref) {
    boolean r = (keyType > HARD) && (key == ref);
    r = r || ((valueType > HARD) && (value == ref));
    if (r) {
      if (keyType > HARD) ((Reference)key).clear();
      if (valueType > HARD) {
        ((Reference)value).clear();
      } else if (purgeValues) {
        value = null;
      }
    }
    return r;
  }
}

代码示例来源:origin: google/guava

public void testDrainKeyReferenceQueueOnWrite() {
 for (CacheBuilder<Object, Object> builder : allKeyValueStrengthMakers()) {
  LocalCache<Object, Object> map = makeLocalCache(builder.concurrencyLevel(1));
  if (map.usesKeyReferences()) {
   Segment<Object, Object> segment = map.segments[0];
   Object keyOne = new Object();
   int hashOne = map.hash(keyOne);
   Object valueOne = new Object();
   Object keyTwo = new Object();
   Object valueTwo = new Object();
   map.put(keyOne, valueOne);
   ReferenceEntry<Object, Object> entry = segment.getEntry(keyOne, hashOne);
   @SuppressWarnings("unchecked")
   Reference<Object> reference = (Reference) entry;
   reference.enqueue();
   map.put(keyTwo, valueTwo);
   assertFalse(map.containsKey(keyOne));
   assertFalse(map.containsValue(valueOne));
   assertNull(map.get(keyOne));
   assertEquals(1, map.size());
   assertNull(segment.keyReferenceQueue.poll());
  }
 }
}

代码示例来源:origin: google/guava

public void testDrainKeyReferenceQueueOnWrite() {
 for (MapMaker maker : allWeakKeyStrengthMakers()) {
  MapMakerInternalMap<Object, Object, ?, ?> map = makeMap(maker.concurrencyLevel(1));
  if (maker.getKeyStrength() == Strength.WEAK) {
   Segment<Object, Object, ?, ?> segment = map.segments[0];
   Object keyOne = new Object();
   int hashOne = map.hash(keyOne);
   Object valueOne = new Object();
   Object keyTwo = new Object();
   Object valueTwo = new Object();
   map.put(keyOne, valueOne);
   InternalEntry<Object, Object, ?> entry = segment.getEntry(keyOne, hashOne);
   @SuppressWarnings("unchecked")
   Reference<Object> reference = (Reference) entry;
   reference.enqueue();
   map.put(keyTwo, valueTwo);
   assertFalse(map.containsKey(keyOne));
   assertFalse(map.containsValue(valueOne));
   assertNull(map.get(keyOne));
   assertEquals(1, map.size());
   assertNull(segment.getKeyReferenceQueueForTesting().poll());
  }
 }
}

代码示例来源:origin: redisson/redisson

private V unfold(Reference<V> ref) {
  if (ref == null) {
    return null;
  }
  return ref.get();
}

代码示例来源:origin: GitLqr/LQRWeChat

public void detachView() {
  if (mViewRef != null) {
    mViewRef.clear();
    mViewRef = null;
  }
}

代码示例来源:origin: google/guava

public void testDrainValueReferenceQueueOnWrite() {
 for (CacheBuilder<Object, Object> builder : allKeyValueStrengthMakers()) {
  LocalCache<Object, Object> map = makeLocalCache(builder.concurrencyLevel(1));
  if (map.usesValueReferences()) {
   Segment<Object, Object> segment = map.segments[0];
   Object keyOne = new Object();
   int hashOne = map.hash(keyOne);
   Object valueOne = new Object();
   Object keyTwo = new Object();
   Object valueTwo = new Object();
   map.put(keyOne, valueOne);
   ReferenceEntry<Object, Object> entry = segment.getEntry(keyOne, hashOne);
   ValueReference<Object, Object> valueReference = entry.getValueReference();
   @SuppressWarnings("unchecked")
   Reference<Object> reference = (Reference) valueReference;
   reference.enqueue();
   map.put(keyTwo, valueTwo);
   assertFalse(map.containsKey(keyOne));
   assertFalse(map.containsValue(valueOne));
   assertNull(map.get(keyOne));
   assertEquals(1, map.size());
   assertNull(segment.valueReferenceQueue.poll());
  }
 }
}

代码示例来源:origin: nostra13/Android-Universal-Image-Loader

@Override
public View getWrappedView() {
  return viewRef.get();
}

代码示例来源:origin: GitLqr/LQRWeChat

public void detachView() {
  if (mViewRef != null) {
    mViewRef.clear();
    mViewRef = null;
  }
}

代码示例来源:origin: google/guava

public void testDrainKeyReferenceQueueOnRead() {
 for (CacheBuilder<Object, Object> builder : allKeyValueStrengthMakers()) {
  LocalCache<Object, Object> map = makeLocalCache(builder.concurrencyLevel(1));
  if (map.usesKeyReferences()) {
   Segment<Object, Object> segment = map.segments[0];
   Object keyOne = new Object();
   int hashOne = map.hash(keyOne);
   Object valueOne = new Object();
   Object keyTwo = new Object();
   map.put(keyOne, valueOne);
   ReferenceEntry<Object, Object> entry = segment.getEntry(keyOne, hashOne);
   @SuppressWarnings("unchecked")
   Reference<Object> reference = (Reference) entry;
   reference.enqueue();
   for (int i = 0; i < SMALL_MAX_SIZE; i++) {
    map.get(keyTwo);
   }
   assertFalse(map.containsKey(keyOne));
   assertFalse(map.containsValue(valueOne));
   assertNull(map.get(keyOne));
   assertEquals(0, map.size());
   assertNull(segment.keyReferenceQueue.poll());
  }
 }
}

代码示例来源:origin: nostra13/Android-Universal-Image-Loader

@Override
public boolean isCollected() {
  return viewRef.get() == null;
}

代码示例来源:origin: wildfly/wildfly

boolean purge(Reference ref) {
    boolean r = (keyType > HARD) && (key == ref);
    r = r || ((valueType > HARD) && (value == ref));
    if (r) {
      if (keyType > HARD) ((Reference)key).clear();
      if (valueType > HARD) {
        ((Reference)value).clear();
      } else if (purgeValues) {
        value = null;
      }
    }
    return r;
  }
}

代码示例来源:origin: google/guava

public void testDrainValueReferenceQueueOnWrite() {
 for (MapMaker maker : allWeakValueStrengthMakers()) {
  MapMakerInternalMap<Object, Object, ?, ?> map = makeMap(maker.concurrencyLevel(1));
  if (maker.getValueStrength() == Strength.WEAK) {
   Segment<Object, Object, ?, ?> segment = map.segments[0];
   Object keyOne = new Object();
   int hashOne = map.hash(keyOne);
   Object valueOne = new Object();
   Object keyTwo = new Object();
   Object valueTwo = new Object();
   map.put(keyOne, valueOne);
   @SuppressWarnings("unchecked")
   WeakValueEntry<Object, Object, ?> entry =
     (WeakValueEntry<Object, Object, ?>) segment.getEntry(keyOne, hashOne);
   WeakValueReference<Object, Object, ?> valueReference = entry.getValueReference();
   @SuppressWarnings("unchecked")
   Reference<Object> reference = (Reference) valueReference;
   reference.enqueue();
   map.put(keyTwo, valueTwo);
   assertFalse(map.containsKey(keyOne));
   assertFalse(map.containsValue(valueOne));
   assertNull(map.get(keyOne));
   assertEquals(1, map.size());
   assertNull(segment.getValueReferenceQueueForTesting().poll());
  }
 }
}

代码示例来源:origin: commons-collections/commons-collections

/**
 * Gets the key from the entry.
 * This method dereferences weak and soft keys and thus may return null.
 * 
 * @return the key, which may be null if it was garbage collected
 */
public Object getKey() {
  return (parent.keyType > HARD) ? ((Reference) key).get() : key;
}

代码示例来源:origin: google/guava

/**
 * Repeatedly dequeues references from the queue and invokes {@link
 * FinalizableReference#finalizeReferent()} on them until the queue is empty. This method is a
 * no-op if the background thread was created successfully.
 */
void cleanUp() {
 if (threadStarted) {
  return;
 }
 Reference<?> reference;
 while ((reference = queue.poll()) != null) {
  /*
   * This is for the benefit of phantom references. Weak and soft references will have already
   * been cleared by this point.
   */
  reference.clear();
  try {
   ((FinalizableReference) reference).finalizeReferent();
  } catch (Throwable t) {
   logger.log(Level.SEVERE, "Error cleaning up after reference.", t);
  }
 }
}

代码示例来源:origin: google/guava

public void testDrainKeyReferenceQueueOnRead() {
 for (MapMaker maker : allWeakKeyStrengthMakers()) {
  MapMakerInternalMap<Object, Object, ?, ?> map = makeMap(maker.concurrencyLevel(1));
  if (maker.getKeyStrength() == Strength.WEAK) {
   Segment<Object, Object, ?, ?> segment = map.segments[0];
   Object keyOne = new Object();
   int hashOne = map.hash(keyOne);
   Object valueOne = new Object();
   Object keyTwo = new Object();
   map.put(keyOne, valueOne);
   InternalEntry<Object, Object, ?> entry = segment.getEntry(keyOne, hashOne);
   @SuppressWarnings("unchecked")
   Reference<Object> reference = (Reference) entry;
   reference.enqueue();
   for (int i = 0; i < SMALL_MAX_SIZE; i++) {
    Object unused = map.get(keyTwo);
   }
   assertFalse(map.containsKey(keyOne));
   assertFalse(map.containsValue(valueOne));
   assertNull(map.get(keyOne));
   assertEquals(0, map.size());
   assertNull(segment.getKeyReferenceQueueForTesting().poll());
  }
 }
}

代码示例来源:origin: commons-collections/commons-collections

/**
 * Gets the value from the entry.
 * This method dereferences weak and soft value and thus may return null.
 * 
 * @return the value, which may be null if it was garbage collected
 */
public Object getValue() {
  return (parent.valueType > HARD) ? ((Reference) value).get() : value;
}

代码示例来源:origin: commons-collections/commons-collections

public Object setValue(Object object) {
  Object old = getValue();
  if (valueType > HARD) ((Reference)value).clear();
  value = toReference(valueType, object, hash);
  return old;
}

代码示例来源:origin: google/guava

public void testDrainValueReferenceQueueOnRead() {
 for (CacheBuilder<Object, Object> builder : allKeyValueStrengthMakers()) {
  LocalCache<Object, Object> map = makeLocalCache(builder.concurrencyLevel(1));
  if (map.usesValueReferences()) {
   Segment<Object, Object> segment = map.segments[0];
   Object keyOne = new Object();
   int hashOne = map.hash(keyOne);
   Object valueOne = new Object();
   Object keyTwo = new Object();
   map.put(keyOne, valueOne);
   ReferenceEntry<Object, Object> entry = segment.getEntry(keyOne, hashOne);
   ValueReference<Object, Object> valueReference = entry.getValueReference();
   @SuppressWarnings("unchecked")
   Reference<Object> reference = (Reference) valueReference;
   reference.enqueue();
   for (int i = 0; i < SMALL_MAX_SIZE; i++) {
    map.get(keyTwo);
   }
   assertFalse(map.containsKey(keyOne));
   assertFalse(map.containsValue(valueOne));
   assertNull(map.get(keyOne));
   assertEquals(0, map.size());
   assertNull(segment.valueReferenceQueue.poll());
  }
 }
}

代码示例来源:origin: hibernate/hibernate-orm

@SuppressWarnings("unchecked")
final V dereferenceValue(Object value) {
  if ( value instanceof KeyReference ) {
    return ( (Reference<V>) value ).get();
  }
  return (V) value;
}

相关文章