2014-02-26 54 views
0

如果你讀了sourceReadOnyObjectWrapper,你會看到getReadOnlyProperty()方法使用一個簡單的單一實例方案,即Javafx - 有沒有垃圾回收的ReadOnlyDoubleWrappers?

ReadOnlyPropertyImp readOnlyProperty; 

public ReadOnlyDoubleProperty getReadOnlyProperty(){ 
    if(readOnlyProperty == null){ 
     readOnlyProperty = new ReadOnlyPropertyImp(); 
    } 
    return readOnlyProperty; 
} 

其中ReadOnlyPropertyImp是延長ReadOnlyDoubleProperty嵌套類。在我看來,不過,如果我是做

ReadOnlyDoubleWrapper wrapper= new ReadOnlyDoubleWrapper(); 
ReadOnlyDoubleProperty property = wrapper.getReadOnlyProperty(); 

現在既不wrapper也不property將永遠是垃圾收集,因爲每個蘊含着濃厚參考其他。這是否準確?

+0

如果所有對包裝和屬性的引用都丟失,它們都將被垃圾收集。他們互相引用並不重要。如果沒有任何一個引用它們,那麼沒有活物可以接觸到它們,並且它們會被gc化。 –

回答

0

根據我的評論,如果兩個對象的所有引用都超出了範圍,則這些值將被GC化。看看這個代碼:

public class Main 
{ 
static WeakReference<StrongReference> wr1; 
static WeakReference<StrongReference> wr2; 

public static void main(String[] args) throws Exception { 
    Main m = new Main(); 

    System.out.println(wr1.get() == null); 
    System.out.println(wr2.get() == null); 

    int count = 0; 
    while (count < 5) { 
     Thread.sleep(1000); 
     //attempt to invoke GC 
     System.out.println("GC Hint"); 
     System.gc(); 
     count ++; 
    } 

    System.out.println(wr1.get() == null); 
    System.out.println(wr2.get() == null); 
} 

public Main() { 
    wr1 = new WeakReference<StrongReference>(new StrongReference()); 
    wr2 = new WeakReference<StrongReference>(new StrongReference()); 
    wr1.get().setRef(wr2.get()); 
    wr2.get().setRef(wr1.get()); 

    System.out.println("SR 1 references - " + wr1.get().getRef().toString()); 
    System.out.println("SR 2 references - " + wr2.get().getRef().toString()); 
} 


private class StrongReference { 
    private Object myRef; 

    public void setRef(Object o) { 
     myRef = o; 
    } 

    public Object getRef() { 
     return myRef; 
    } 
} 
} 

輸出:

SR 1 references - [email protected] 
SR 2 references - [email protected] 
false 
false 
GC Hint 
GC Hint 
GC Hint 
GC Hint 
GC Hint 
true 
true 

在該代碼中,我有StrongReference類型的兩個對象,其中參考海誓山盟。你會認爲他們永遠不會被GC,但他們可以。我將它們包裝在一個WeakReference對象中,以便在它們創建後打斷它們的引用鏈,並允許GC抓住它們。儘管它們引用了彼此,但值仍然會從WeakReference調用get()的返回null,因爲GC已經清除了它們。我應該注意的是GC可能不會在5秒的循環中運行。我只是提供一個提示給JVM來執行GC,而不是實際調用,所以結果可能會有所不同