强引用:
当内存不够时,宁愿抛出OutOfMemoryError错误,也不会去回收。
Object object = new Object();
String str = "hello";
显示的置null或者脱离其作用域范围,不存在任何引用时即可以被回收。
应用:
ArrayList源码:remove+clear
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
elementData[--size] = null这一句就是显示地将List中的对象置null来是JVM来执行GC操作。
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
同理上面的循环体干的也是这样的活。
软引用:
如果一个对象关联软引用,这当内存不够时才会去回收它,否则不会主动去回收。
SoftReference<String> sr = new SoftReference<String>(new String("hello"));
System.out.println(sr.get()); //输出为hello
应用:
软引用用来解决OOM问题,实现内存敏感的高速缓存。
例如浏览器的后退按钮。按后退时,这个后退时显示的网页内容是重新进行请求还是从缓存中取出呢?这就要看具体的实现策略了。
(1)如果一个网页在浏览结束时就进行内容的回收,则按后退查看前面浏览过的页面时,需要重新构建
(2)如果将浏览过的网页存储到内存中会造成内存的大量浪费,甚至会造成内存溢出
这时候就可以使用软引用:
Browser prev = new Browser(); // 获取页面进行浏览
SoftReference sr = new SoftReference(prev); // 浏览完毕后置为软引用
if(sr.get()!=null){
rev = (Browser) sr.get(); // 还没有被回收器回收,直接获取
}else{
prev = new Browser(); // 由于内存吃紧,所以对软引用的对象回收了
sr = new SoftReference(prev); // 重新构建
}
弱引用:
弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。
WeakReference<String> sr1 = new WeakReference<String>(new String("hello"));
System.out.println(sr1.get()); //输出为hello
System.gc(); //通知JVM的gc进行垃圾回收
System.out.println(sr1.get()); //输出为null
弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。
虚引用:
如果一个对象与虚引用关联,则跟没有引用与之关联一样,在任何时候都可能被垃圾回收器回收。
虚引用主要用来跟踪对象被垃圾回收器回收的活动。虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列 (ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。
ReferenceQueue<String> queue = new ReferenceQueue<String>();
PhantomReference<String> pr = new PhantomReference<String>(new String("hello"), queue);
System.out.println(pr.get()); //输出为null
参考文献:
http://blog.youkuaiyun.com/mazhimazh/article/details/19752475
http://www.cnblogs.com/dolphin0520/p/3784171.html