参考:
Java Reference详解 .
这篇讲的很清楚!!理解这些引用类型 注意一点,当JVM回收时,如果有回收引用队列queue,会把回收的referent加入到回收队列中。从而可实现对象回收时的通知,进行一定的工作。如WeakHashMap(用于回收key为null的entry) , DirectByteBuffer中的cleaner(用于回收堆外内存,因为堆外内存的回收不由JVM管理。)
Java中的强引用,软引用,弱引用,虚引用有什么用?
《Effective Java》中正常是不建议使用这些引用Finalizer或者Cleaner来回收对象的,因为回收线程优先级不够高,回收不够及时,可能会导致严重的GC问题。如果想手动管理对象的回收,可以使类实现AutoCloseable接口,当需要释放对象的时候使客户端调用close方法。
弱引用的Java应用:
ThreadLocal(ThreadLocalMap.Entry中key为弱引用,这样如果key为null的话,有些方法如resize会清空entry中的value,垃圾回收的时候就会回收该entry)
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
WeakHashMap(key为弱引用的HashMap)
软引用的Java应用:
//Class中的缓存
private volatile transient SoftReference<ReflectionData<T>> reflectionData;
// Incremented by the VM on each call to JVM TI RedefineClasses()
// that redefines this class or a superclass.
private volatile transient int classRedefinedCount = 0;
// Lazily create and cache ReflectionData
private ReflectionData<T> reflectionData() {
SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
int classRedefinedCount = this.classRedefinedCount;
ReflectionData<T> rd;
if (useCaches &&
reflectionData != null &&
(rd = reflectionData.get()) != null &&
rd.redefinedCount == classRedefinedCount) {
return rd;
}
// else no SoftReference or cleared SoftReference or stale ReflectionData
// -> create and replace new instance
return newReflectionData(reflectionData, classRedefinedCount);
}
其实SoftReference和WeakReference都经常用来作为缓存来使用,不过WeakReference更容易被清除而已。
Java的守护线程参考:
从Daemons到finalize timed out after 10 seconds