Java中的引用类型分为四种:强引用
、软引用
、弱引用
和虚引用
强引用
例如:Object o = new Object()
就是强引用关系,这是一种最为常见的引用关系,而被强引用
关联的对象,只要引用关系还存在,则不会被垃圾收集器回收。
软引用
软引用
一般关联的对象都有用但非必须的对象。被软引用
关联的对象,在系统发生OOM
前,会被垃圾收集器列入回收范围之中进行第二次回收,如若回收完依旧没有足够内存,则抛出内存溢出异常。
Java中使用SoftReference
类实现软引用:
package java.lang.ref;
/**
* Soft reference objects, which are cleared at the discretion of the garbage
* collector in response to memory demand. Soft references are most often used
* to implement memory-sensitive caches.
*
* <p> Suppose that the garbage collector determines at a certain point in time
* that an object is <a href="package-summary.html#reachability">softly
* reachable</a>. At that time it may choose to clear atomically all soft
* references to that object and all soft references to any other
* softly-reachable objects from which that object is reachable through a chain
* of strong references. At the same time or at some later time it will
* enqueue those newly-cleared soft references that are registered with
* reference queues.
*
* <p> All soft references to softly-reachable objects are guaranteed to have
* been cleared before the virtual machine throws an
* <code>OutOfMemoryError</code>. Otherwise no constraints are placed upon the
* time at which a soft reference will be cleared or the order in which a set
* of such references to different objects will be cleared. Virtual machine
* implementations are, however, encouraged to bias against clearing
* recently-created or recently-used soft references.
*
* <p> Direct instances of this class may be used to implement simple caches;
* this class or derived subclasses may also be used in larger data structures
* to implement more sophisticated caches. As long as the referent of a soft
* reference is strongly reachable, that is, is actually in use, the soft
* reference will not be cleared. Thus a sophisticated cache can, for example,
* prevent its most recently used entries from being discarded by keeping
* strong referents to those entries, leaving the remaining entries to be
* discarded at the discretion of the garbage collector.
*
* @author Mark Reinhold
* @since 1.2
*/
public class SoftReference<T> extends Reference<T> {
/**
* Timestamp clock, updated by the garbage collector
*/
static private long clock;
/**
* Timestamp updated by each invocation of the get method. The VM may use
* this field when selecting soft references to be cleared, but it is not
* required to do so.
*/
private long timestamp;
/**
* Creates a new soft reference that refers to the given object. The new
* reference is not registered with any queue.
*
* @param referent object the new soft reference will refer to
*/
public SoftReference(T referent) {
super(referent);
this.timestamp = clock;
}
/**
* Creates a new soft reference that refers to the given object and is
* registered with the given queue.
*
* @param referent object the new soft reference will refer to
* @param q the queue with which the reference is to be registered,
* or <tt>null</tt> if registration is not required
*
*/
public SoftReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
this.timestamp = clock;
}
/**
* Returns this reference object's referent. If this reference object has
* been cleared, either by the program or by the garbage collector, then
* this method returns <code>null</code>.
*
* @return The object to which this reference refers, or
* <code>null</code> if this reference object has been cleared
*/
public T get() {
T o = super.get();
if (o != null && this.timestamp != clock)
this.timestamp = clock;
return o;
}
}
从代码中可以得知,我们创建一个软引用对象的方式如下:
SoftReference<Object> softReference = new SoftReference<>(new Object());
因为软引用对象有可能会被清理掉,因此使用软引用对象时一般需要进行校验:
Object obj = softReference.get();
if( obj == null){
softReference = new SoftReference<>(new Object());
}
obj = softReference.get();
其实也不难发现,软引用
比较适合应用在需要缓存
的场景,例如加载图片或者一些网络资源时。
软引用
的被标记清理的原理与弱引用
一致,参照弱引用
中的解释。
弱引用
同样是用来描述非必须的对象,引用的强度比软引用
更弱,被弱引用
关联的对象,只能存在到下次垃圾收集发生为止。当垃圾收集开始,无论内存是否足够,弱引用
关联的对象都将会被回收掉。
Java中使用WeakReference
来实现弱引用:
package java.lang.ref;
/**
* Weak reference objects, which do not prevent their referents from being
* made finalizable, finalized, and then reclaimed. Weak references are most
* often used to implement canonicalizing mappings.
*
* <p> Suppose that the garbage collector determines at a certain point in time
* that an object is <a href="package-summary.html#reachability">weakly
* reachable</a>. At that time it will atomically clear all weak references to
* that object and all weak references to any other weakly-reachable objects
* from which that object is reachable through a chain of strong and soft
* references. At the same time it will declare all of the formerly
* weakly-reachable objects to be finalizable. At the same time or at some
* later time it will enqueue those newly-cleared weak references that are
* registered with reference queues.
*
* @author Mark Reinhold
* @since 1.2
*/
public class WeakReference<T> extends Reference<T> {
/**
* Creates a new weak reference that refers to the given object. The new
* reference is not registered with any queue.
*
* @param referent object the new weak reference will refer to
*/
public WeakReference(T referent) {
super(referent);
}
/**
* Creates a new weak reference that refers to the given object and is
* registered with the given queue.
*
* @param referent object the new weak reference will refer to
* @param q the queue with which the reference is to be registered,
* or <tt>null</tt> if registration is not required
*/
public WeakReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
}
}
使用方式与软引用也是类似的
重点关注一下使用场景,在Java中,为了确保某个对象会被垃圾收集器清理掉,我们常常会将引用置为null
Object obj = new Object();
obj = null;
当我们将obj
设置为null
时,原来指向的Object
对象将没有强引用
再指向他,因此,该对象是不可达的
,将会被作为垃圾收集掉
其实一般情况下,随着方法执行完毕,大多数对象的引用都会随着方法栈
的出栈而释放掉,而其指向的对象也就变为不可达的,因此无需手动将其设置为null
弱引用
的使用场景最多的也是最为缓存
来使用,我们定义需要缓存的对象
WeakReference<Object> weakReference = new WeakReference<>(new Object());
当我们需要引用时
Object o = weakReference.get();
if(o == null){
weakReference = new WeakReference<>(new Object());
}
o = weakReference.get();
需要注意的是,此时o
是作为强引用
指向Object对象的,只要o
的关联关系存在,那么Object
对象是无法被回收的,当我们的方法出栈,或者说Object
没有任何强引用
关系,只存在弱引用
关系时,在此期间如果没有其他强引用
再次指向它,那么下次垃圾收集的时候,Object
对象就会被作为垃圾清理掉。
虚引用
又称为幽灵引用
、幻影引用
。它是引用关系中最弱的一个,虚引用
的存在完全不会对对象的生存时间产生影响,同时我们也无法通过虚引用
获取对象实例。使用虚引用
关联的目的是:为了能够在该对象被回收时收到通知
。
在Java中使用PhantomReference
实现虚引用
package java.lang.ref;
/**
* Phantom reference objects, which are enqueued after the collector
* determines that their referents may otherwise be reclaimed. Phantom
* references are most often used for scheduling pre-mortem cleanup actions in
* a more flexible way than is possible with the Java finalization mechanism.
*
* <p> If the garbage collector determines at a certain point in time that the
* referent of a phantom reference is <a
* href="package-summary.html#reachability">phantom reachable</a>, then at that
* time or at some later time it will enqueue the reference.
*
* <p> In order to ensure that a reclaimable object remains so, the referent of
* a phantom reference may not be retrieved: The <code>get</code> method of a
* phantom reference always returns <code>null</code>.
*
* <p> Unlike soft and weak references, phantom references are not
* automatically cleared by the garbage collector as they are enqueued. An
* object that is reachable via phantom references will remain so until all
* such references are cleared or themselves become unreachable.
*
* @author Mark Reinhold
* @since 1.2
*/
public class PhantomReference<T> extends Reference<T> {
/**
* Returns this reference object's referent. Because the referent of a
* phantom reference is always inaccessible, this method always returns
* <code>null</code>.
*
* @return <code>null</code>
*/
public T get() {
return null;
}
/**
* Creates a new phantom reference that refers to the given object and
* is registered with the given queue.
*
* <p> It is possible to create a phantom reference with a <tt>null</tt>
* queue, but such a reference is completely useless: Its <tt>get</tt>
* method will always return null and, since it does not have a queue, it
* will never be enqueued.
*
* @param referent the object the new phantom reference will refer to
* @param q the queue with which the reference is to be registered,
* or <tt>null</tt> if registration is not required
*/
public PhantomReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
}
}
源码中也印证了无法获得虚引用
对象的说法,get方法
始终都是返回null
同时也可以发现,虚引用
只提供了一个构造方法
ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
PhantomReference<Object> phantomReference = new PhantomReference<>(new Object(), referenceQueue);
这种形式的构造方法在软引用
和弱引用
中同样存在,ReferenceQueue
是一个保存引用的队列,当引用关系发生改变时(被垃圾收集器收集),该引用会被添加到队列中
可以通过下面代码进行验证(软引用
和弱引用
的不在列举):
ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
PhantomReference<Object> phantomReference = new PhantomReference<>(new Object(), referenceQueue);
Reference reference1;
while ((reference1 = referenceQueue.poll()) != null){
System.out.println("reference1:"+ reference1);
}
System.gc();
TimeUnit.SECONDS.sleep(2);
Reference reference2;
while ((reference2 = referenceQueue.poll()) != null){
System.out.println("reference2:"+reference2);
}
执行结果:reference2:java.lang.ref.PhantomReference@6b884d57
当gc
发生是,Object
对象被垃圾收集器回收掉,同时引用信息会被保存到referenceQueue
队列中,但是因为PhantomReference
的get方法
返回的都是null
,因此即便可以将虚引用
对象出队,也是没有任何意义的。