Java 引用方式

    Java中的引用方式有StrongReference, SoftReference, WeakReference和PhantomReference。先来看一个来mindprod 的一个图表:

Soft vs Weak vs Phantom References Type Purpose Use When GCed Implementing Class
Strong Reference An ordinary reference. Keeps objects alive as long as they are referenced. normal reference. Any object not pointed to can be reclaimed. default
Soft Reference Keeps objects alive provided there’s enough memory. to keep objects alive even after clients have removed their references (memory-sensitive caches), in case clients start asking for them again by key. After a first gc pass, the JVM decides it still needs to reclaim more space. java.lang.ref. SoftReference
Weak Reference Keeps objects alive only while they’re in use (reachable) by clients. Containers that automatically delete objects no longer in use. After gc determines the object is only weakly reachable java.lang.ref. WeakReference
java.util. WeakHashMap
Phantom Reference Lets you clean up after finalization but before the space is reclaimed (replaces or augments the use of finalize ()) Special clean up processing After finalization. java.lang.ref. PhantomReference

 

    1、StrongReference: 是Java中默认的引用方式。当它指向某个对象时,该对象不会被回收;当它不再指向该对象,且该对象没有其它的引用指向时,在GC被执行后,可以回收该对象所占用内存。

    代码示例1:

		// 在栈内存创建Object的引用
		Object object = null;
		// 在堆内存创建Object对象,并使object引用指向刚刚创建的Object对象
		object = new Object();

     执行完上述代码,内存分布如下图:


Java 引用方式_第1张图片
     如果此时系统调用GC,object指向的对象不会被回收。

 

    代码示例2:

// 断开引用
object = null;
 

     执行完上述代码,内存分布如下图:


Java 引用方式_第2张图片
    如果此时系统调用GC,断开object指向前的那个对象会被回收。

 

     2、SoftReference: 当JVM内存不足时,SoftReference指向的对象会被回收。这样的特性,使得SoftReference适合应用到缓存操作。

    使用方式:

		Object object = new Object();
		SoftReference<Object> softRerference = new SoftReference<Object>(object);
		object = null;

 

    3、WeakReference: 当所引用的对象不再有强引用时, 系统调用GC后,该对象会被回收。使用方法类似SoftReference。WeakHashMap的key的类型是WeakReference, 如果没有指向key的强引用,在系统调用GC后,WeakHashMap会删除相关的value对象并回收。

    代码示例:

		// 创建并指向WeakHashMap
		Map<Object, Object> weakHashMap = new WeakHashMap<Object, Object>();
		
		// 创建并指向key
		Object key = new Object();
		
		// 创建并指向value
		Object value = new Object();
		
		// 添加key-value对到WeakHashMap
		weakHashMap.put(key, value);
		
		// 断开key的强引用
		key = null;
 

    4、PhantomReference: 注意它与finalize方法调用的时机。

    5、多说一句 :这些引用方式都具有自己的特性,根据它们的特性完成某个特定的功能!:)

 

你可能感兴趣的:(SoftReference,WeakReference,strongreference,Java引用方式)