轻松了解Java各类引用

强引用

强引用是使用最为普遍的引用,如果一个对象具有强引用,那么垃圾回收器绝不会回收它。如下:

1
Object object = new Object();// 强引用

当内存空间不足,Java虚拟机宁愿抛出OutOfMemoryError错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足的问题。如果不使用时,通过如下方式来弱化引用,如下:

1
object = null;//帮助垃圾收集器回收此对象

显示地设置object为null,或超出对象的生命周期范围,则GC认为该对象不存在引用,这时就可以回收这个对象,具体什么时候回收主要取决于GC的算法实现机制。

举例:

1
2
3
4
public void printBookInfo(){
AkaThinkBook akaThinkBook = new AkaThinkBook();
akaThinkBook.getBookInfo();
}

该方法内部拥有一个强引用akaThinkBook,这个引用将会保存在栈中,而真正的引用对象(new AkaThinkBook())则保存在堆中。当这个方法运行完之后,就会退出方法栈,则引用对象的引用不再存在,这个对象就会被回收。

但如果这个akaThinkBook是全局变量时,就需要在不用这个对象时赋值为null,因为强引用不会被垃圾回收。

强引用在实际开发中占有非常重要的席位,通过ArrayList的实现源代码来了解一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}

在ArrayList类中定义了一个变量elementData数组,在调用clear方法清空数组时可以看到为每个数组内容赋值为null。不同于elementData=null,强引用仍然存在,避免在后续调用 add()等方法添加元素时进行重新的内存分配。使用如clear()方法中释放内存的方法对数组中存放的引用类型特别适用,这样就可以及时释放内存。

软引用

如果一个对象只具有软引用,则内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。

1
2
3
4
//强引用
AkaThinkBook akaThinkBook = new AkaThinkBook();
//软引用
SoftReference<AkaThinkBook> softReference = new SoftReference<AkaThinkBook>(akaThinkBook);

当内存不足时,等价于:

1
2
3
4
5
6
if(JVM.内存不足()){
akaThinkBook = null//转换为软引用
System.gc();// 进行垃圾回收

虚引用在实际中有重要的应用,例如浏览器的后退按钮。按后退时,这个后退时显示的网页内容是重新进行请求还是从缓存中取出呢?这就要看具体的实现策略了。

  1. 如果一个网页在浏览结束时就进行内容的回收,则按后退查看前面浏览过的页面时,需要重新构建
  2. 如果将浏览过的网页存储到内存中会造成内存的大量浪费,甚至会造成内存溢出

这时候就可以使用软引用

1
2
3
4
5
6
7
8
Browser browser = new Browser();//获取页面进行浏览
SoftReference softBrowser = new SoftReference<Browser>(browser);//浏览完毕之后设置为软引用
if(softBrowser != null){
browser = (Browser) softBrowser.get();//如果没有被GC回收,直接获取
}else{
browser = new Browser();//由于内存不足,导致软引用被GC回收,若是现在再使用的话,则直接创建
softBrowser = new SoftReference<Browser>(browser);//重新设置为软引用
}

这样就很好的解决了实际的问题。

软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收器回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中。

弱引用

弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。

1
2
3
4
5
//强引用
AkaThinkBook akaThinkBook = new AkaThinkBook();
//弱引用
WeakReference<AkaThinkBook> weakReference = new WeakReference<AkaThinkBook>(akaThinkBook);
akaThinkBook = null;

当垃圾回收器进行扫描回收时等价于:

1
2
akaThinkBook = null;
System.gc();

如果这个对象是偶尔的使用,并且希望在使用时随时就能获取到,但又不想影响此对象的垃圾收集,那么你应该用 Weak Reference 来记住此对象。

下面的代码会让akaThinkBook变为一个强引用:

1
AkaThinkBook book = weakReference.get();

弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。
当你想引用一个对象,但是这个对象有自己的生命周期,你不想介入这个对象的生命周期,这时候你就是用弱引用。

这个引用不会在对象的垃圾回收判断中产生任何附加的影响。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.akathink.reference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import javax.security.auth.Refreshable;
public class ReferenceDemo {
private static ReferenceQueue<BigFile> referenceQueue = new ReferenceQueue<>();
public static void checkQueue() {
Reference<? extends BigFile> reference = null;
while ((reference = referenceQueue.poll()) != null) {
if (reference != null) {
System.out.println("In queue: " + ((BigFileWeakReference) (reference)).getVideo());
}
}
}
public static void main(String[] args) {
int size = 3;
LinkedList<WeakReference<BigFile>> weakList = new LinkedList<WeakReference<BigFile>>();
for (int i = 0; i < size; i++) {
weakList.add(new BigFileWeakReference(new BigFile("-----Weak Video-----" + i), referenceQueue));
System.out.println("Just created weak: " + weakList.getLast());
}
System.gc();
try { // 下面休息8秒钟,让上面的垃圾回收线程运行完成
Thread.currentThread().sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
checkQueue();
}
}
class BigFile {
private String video;
// 占用空间,让线程进行回收
byte[] b = new byte[2 * 1024];
public BigFile(String video) {
this.video = video;
}
public String getVideo() {
return video;
}
@Override
protected void finalize() throws Throwable {
System.out.println("Finalizing BigFile" + video);
}
}
class BigFileWeakReference extends WeakReference<BigFile> {
private String video;
public BigFileWeakReference(BigFile bigFile, ReferenceQueue<BigFile> referenceQueue) {
super(bigFile, referenceQueue);
this.video = bigFile.getVideo();
}
public String getVideo() {
return video;
}
@Override
protected void finalize() throws Throwable {
System.out.println("Finalizing BigFileWeakReference" + video);
}
}

运行结果

1
2
3
4
5
6
7
8
9
Just created weak: com.akathink.reference.BigFileWeakReference@15db9742
Just created weak: com.akathink.reference.BigFileWeakReference@6d06d69c
Just created weak: com.akathink.reference.BigFileWeakReference@7852e922
Finalizing BigFile-----Weak Video-----2
Finalizing BigFile-----Weak Video-----1
Finalizing BigFile-----Weak Video-----0
In queue: -----Weak Video-----2
In queue: -----Weak Video-----1
In queue: -----Weak Video-----0

虚引用

“虚引用”顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收。

虚引用主要用来跟踪对象被垃圾回收器回收的活动。虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列 (ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之 关联的引用队列中。

总结

Java这四种引用的级别由高到低依次为:

1
强引用 > 软引用 > 弱引用 > 虚引用

通过图来看一下他们之间在垃圾回收时的区别:

Java四类引用总结

当垃圾回收器回收时,某些对象会被回收,某些不会被回收。垃圾回收器会从根对象Object来标记存活的对象,然后将某些不可达的对象和一些引用的对象进行回收。

通过表格来说明一下,如下:

引用类型 被垃圾回收时间 用途 生存时间
强引用 从来不会 对象的一般状态 JVM停止运行时终止
软引用 内存不足时 对象缓存 内存不足时终止
弱引用 垃圾回收时 对象缓存 GC运行后终止
虚引用 Unknown Unknown Unknown

参考资料

http://my.oschina.net/ydsakyclguozi/blog/404389