软引用和强引用

 在Java中,虽然不需要程序员手动去管理对象的生命周期,但是如果希望某些对象具备一定的生命周期的话(比如内存不足时JVM就会自动回收某些对象从而避免OutOfMemory的错误)就需要用到软引用和弱引用了。

  从Java SE2开始,就提供了四种类型的引用:强引用、软引用、弱引用和虚引用。Java中提供这四种引用类型主要有两个目的:第一是可以让程序员通过代码的方式决定某些对象的生命周期;第二是有利于JVM进行垃圾回收。下面来阐述一下这四种类型引用的概念:

  1.强引用(StrongReference)

  强引用就是指在程序代码之中普遍存在的,比如下面这段代码中的object和str都是强引用:

      

Object object = new Object();
String str = "hello";

    只要某个对象有强引用与之关联,JVM必定不会回收这个对象,即使在内存不足的情况下,JVM宁愿抛出OutOfMemory错误也不会回收这种对象。比如下面这段代码:

    

public class Main {
    public static void main(String[] args) {
        new Main().fun1();
    }
     
    public void fun1() {
        Object object = new Object();
        Object[] objArr = new Object[1000];
    }
}

  当运行至Object[] objArr = new Object[1000];这句时,如果内存不足,JVM会抛出OOM错误也不会回收object指向的对象。不过要注意的是,当fun1运行完之后,object和objArr都已经不存在了,所以它们指向的对象都会被JVM回收。

  如果想中断强引用和某个对象之间的关联,可以显示地将引用赋值为null,这样一来的话,JVM在合适的时间就会回收该对象。

  比如Vector类的clear方法中就是通过将引用赋值为null来实现清理工作的:

      

/**
     * Removes the element at the specified position in this Vector.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).  Returns the element that was removed from the Vector.
     *
     * @throws ArrayIndexOutOfBoundsException if the index is out of range
     *         ({@code index < 0 || index >= size()})
     * @param index the index of the element to be removed
     * @return element that was removed
     * @since 1.2
     */
    public synchronized E remove(int index) {
    modCount++;
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);
    Object oldValue = elementData[index];

    int numMoved = elementCount - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                 numMoved);
    elementData[--elementCount] = null; // Let gc do its work

    return (E)oldValue;
    }

   2.软引用(SoftReference)

  软引用是用来描述一些有用但并不是必需的对象,在Java中用java.lang.ref.SoftReference类来表示。对于软引用关联着的对象,只有在内存不足的时候JVM才会回收该对象。因此,这一点可以很好地用来解决OOM的问题,并且这个特性很适合用来实现缓存:比如网页缓存、图片缓存等。

  软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被JVM回收,这个软引用就会被加入到与之关联的引用队列中。下面是一个使用示例:

   

import java.lang.ref.SoftReference;
 
public class Main {
    public static void main(String[] args) {
         
        SoftReference<String> sr = new SoftReference<String>(new String("hello"));
        System.out.println(sr.get());
    }
}

 3.弱引用(WeakReference)

  弱引用也是用来描述非必需对象的,当JVM进行垃圾回收时,无论内存是否充足,都会回收被弱引用关联的对象。在java中,用java.lang.ref.WeakReference类来表示。下面是使用示例:

  

import java.lang.ref.WeakReference;
 
public class Main {
    public static void main(String[] args) {
     
        WeakReference<String> sr = new WeakReference<String>(new String("hello"));
         
        System.out.println(sr.get());
        System.gc();                //通知JVM的gc进行垃圾回收
        System.out.println(sr.get());
    }
}
输出结果为:


hello
null

 第二个输出结果是null,这说明只要JVM进行垃圾回收,被弱引用关联的对象必定会被回收掉。不过要注意的是,这里所说的被弱引用关联的对象是指只有弱引用与之关联,如果存在强引用同时与之关联,则进行垃圾回收时也不会回收该对象(软引用也是如此)。

  弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被JVM回收,这个软引用就会被加入到与之关联的引用队列中。

4.虚引用(PhantomReference)

  虚引用和前面的软引用、弱引用不同,它并不影响对象的生命周期。在java中用java.lang.ref.PhantomReference类表示。如果一个对象与虚引用关联,则跟没有引用与之关联一样,在任何时候都可能被垃圾回收器回收。

  要注意的是,虚引用必须和引用队列关联使用,当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会把这个虚引用加入到与之 关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。如果程序发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。

 

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
 
 
public class Main {
    public static void main(String[] args) {
        ReferenceQueue<String> queue = new ReferenceQueue<String>();
        PhantomReference<String> pr = new PhantomReference<String>(new String("hello"), queue);
        System.out.println(pr.get());
    }
}

 以上内容摘自:http://www.cnblogs.com/dolphin0520/p/3784171.html

  下面自己写一个程序测试一下,分配虚拟机10M内存,然后创建10个1M的对象放到value为SoftReference的map里面,观察是否会进行对象回收。

   

/**
 * -XX:+PrintGCDateStamps -XX:+PrintGCDetails -Xms10M -Xmx10M
 */
package reference;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

public class SoftReferenceTest {

	private static Map<String, SoftReference<byte[]>> map = new HashMap<String, SoftReference<byte[]>>();

	private static final int _1MB = 1024 * 1024;

	private static byte[] temp;

	public static void createSoftReference(int size) {

		for (int i = 0; i < size; i++) {
			temp = new byte[_1MB];
			System.out.println(i + ": " + temp.toString());
			map.put(i + "", new SoftReference<byte[]>(temp));
		}

	}

	public static void main(String[] args) {
		int size = 10;
		SoftReferenceTest.createSoftReference(size);
		System.out.println("**********************************");
		System.gc();
		for (int i = 0; i < size; i++) {
			if (null == map.get(i + "").get()) {
				System.out.println(i + ": " + "null");
			} else {
				System.out.println(i + ": " + map.get(i + "").get().toString());
			}
		}
	}
}

  输出为:

   

0: [B@1fc4bec
1: [B@dc8569
2016-05-06T21:00:39.126+0800: [GC [DefNew: 2331K->158K(3072K), 0.0022560 secs] 2331K->2206K(9920K), 0.0022782 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
2: [B@150bd4d
3: [B@1bc4459
2016-05-06T21:00:39.129+0800: [GC [DefNew: 2237K->158K(3072K), 0.0013200 secs] 4285K->4254K(9920K), 0.0013378 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
4: [B@6e1408
5: [B@e53108
2016-05-06T21:00:39.130+0800: [GC [DefNew: 2281K->158K(3072K), 0.0012987 secs] 6377K->6302K(9920K), 0.0013173 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
6: [B@19189e1
7: [B@1f33675
2016-05-06T21:00:39.132+0800: [GC [DefNew: 2219K->2219K(3072K), 0.0000063 secs][Tenured: 6144K->6144K(6848K), 0.0031130 secs] 8364K->8350K(9920K), [Perm : 2096K->2096K(12288K)], 0.0031569 secs] [Times: user=0.02 sys=0.00, real=0.00 secs] 
2016-05-06T21:00:39.135+0800: [Full GC [Tenured: 6144K->1169K(6848K), 0.0036361 secs] 8350K->1169K(9920K), [Perm : 2096K->2090K(12288K)], 0.0036682 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
8: [B@1690726
9: [B@5483cd
**********************************
2016-05-06T21:00:39.139+0800: [Full GC (System) [Tenured: 1169K->3217K(6848K), 0.0033829 secs] 3226K->3217K(9920K), [Perm : 2090K->2090K(12288K)], 0.0034101 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
0: null
1: null
2: null
3: null
4: null
5: null
6: null
7: [B@1f33675
8: [B@1690726
9: [B@5483cd
Heap
 def new generation   total 3072K, used 60K [0x03ad0000, 0x03e20000, 0x03e20000)
  eden space 2752K,   2% used [0x03ad0000, 0x03adf3f8, 0x03d80000)
  from space 320K,   0% used [0x03dd0000, 0x03dd0000, 0x03e20000)
  to   space 320K,   0% used [0x03d80000, 0x03d80000, 0x03dd0000)
 tenured generation   total 6848K, used 3217K [0x03e20000, 0x044d0000, 0x044d0000)
   the space 6848K,  46% used [0x03e20000, 0x041447c0, 0x04144800, 0x044d0000)
 compacting perm gen  total 12288K, used 2096K [0x044d0000, 0x050d0000, 0x084d0000)
   the space 12288K,  17% used [0x044d0000, 0x046dc0a0, 0x046dc200, 0x050d0000)
No shared spaces configured.

 

猜你喜欢

转载自chenghao666.iteye.com/blog/2296445