Java 中對象引用的類型 |
Object Reference Types in Java |
弱引用早有耳聞,但從來沒去認(rèn)真看過。前天改編陳維雷先生的下雪動畫時,發(fā)現(xiàn)他使用了弱引用,于是趁機(jī)把 Java 的對象引用類型看了個究竟。 |
I've heard of weak reference for a long time, but have never study it seriously yet. The day before yesterday, when I was modifying Mr. William Chen's snowing animation, I saw weak reference was utilized, and then took the chance to read the details of Java's reference type. |
除了通常意義下的強(qiáng)引用,包 java.lang.ref 還定義了其他三種平時不太用到的引用:軟引用、弱引用和虛引用,但 API 文檔的解釋比較含糊。我在網(wǎng)上搜到了一些資料,簡單歸納一下。 |
Except the strong reference of common purpose, package java.lang.ref defines three other references which are less often used: soft reference, weak reference and phantom reference, but they have obscure explanations in the API documention. I searched online and got some stuffs and here are my summaries. |
強(qiáng)引用。當(dāng)一個對象具有強(qiáng)引用時,Java 虛擬機(jī)寧愿拋出 OutOfMemeryError,也絕不讓垃圾回收器回收它。 |
Strong Reference. When an object holds strong references, Java Virtue Machine would rather throw an OutOfMemeryError than let garbage collector (GC) collect it. |
軟引用。當(dāng)一個對象只具有軟引用時,垃圾回收器只在內(nèi)存不足的時候才回收它。 |
Soft Reference. When an object holds only soft references, GC collects it only if there is not enough memory. |
弱引用。當(dāng)一個對象只具有弱引用時,一旦被垃圾回收器發(fā)現(xiàn)就會被回收。因為垃圾回收器是一個優(yōu)先級很低的線程,所以弱引用對象也不一定會馬上就會被回收。 |
Weak Reference. When an object holds only weak references, GC collects it as soon as finds it. GC is a thread of very low priority, so a weak reference object may not be collected immediately. |
虛引用。虛引用和對象的生命周期無關(guān)。虛引用必須和引用隊列聯(lián)合使用,對象將被回收前,其虛引用將被加入到引用隊列。虛引用只是用來監(jiān)視對象的回收。 |
Phantom Reference. Phantom reference has nothing to do with the life cycle of an object. Phantom reference must be used together with reference queue, and the object's phantom reference will be added into that reference queue right before collected. Phantom reference is only used to monitor object collecting. |
從以上是否能看出,一個對象不能同時具有軟引用和弱引用? |
From above shall we say that an object can't have a soft reference and a weak reference at the same time? |