2014-07-24 15 views
0

我最近試圖理解java.util.WeakHashMap。爲什麼WeakReferenced對象不能被WeakHashMap去掉

但是,當我使用WeakReference來包裝一個字符串時,WeakHash沒有完成Entry。

另請注意,我正在清除主線程中的WeakReference,然後在線程方法內引用它。

執行時,while循環根本沒有中斷!

public class WeakHashMapTotorial 
{ 
    private static Map<String, String> map; 

    public static void main(String args[]) 
    { 
     WeakReference<String> s = new WeakReference<String>("Maine"); 
     map = new WeakHashMap<>(); 
     map.put(s.get(), "Augusta"); 

     Runnable runner = new Runnable() 
     { 
      public void run() 
      { 
       while (map.containsKey("Maine")) 
       { 
        try 
        { 
         Thread.sleep(1000); 
        } catch (InterruptedException ignored) 
        {} 
        System.out.println("Thread waiting"); 
        System.gc(); 
       } 
      } 
     }; 
     Thread t = new Thread(runner); 
     t.start(); 
     System.out.println("Main waiting"); 
     try 
     { 
      t.join(); 
     } catch (InterruptedException ignored) 
     {} 
     s.clear(); 

    } 
} 

回答

1

您使用正在舉行由實習字符串池的字符串,請嘗試以下操作:

WeakReference<String> s = new WeakReference<String>(new String("Maine")); 
    map = new WeakHashMap<>(); 
    map.put(s.get(), "Augusta"); 

此實習的效果在Java Language Spec

另外描述,字符串文字始終指類 字符串的相同實例。這是因爲字符串文字 - 或者更一般地說是字符串 (常量表達式的值(§15.28)) - 被「實施」爲 ,以便使用方法String.intern共享唯一實例。

+0

謝謝克里斯。我現在得到了缺失的位:) – Maas

2

圍繞String常量包圍WeakReference將不起作用。字符串常量是interned,這意味着引用永遠不會消失。另外,你的代碼在運行方法中保持對同一個常量的引用,進一步保證了強大的引用。

+0

字符串常量*總是*實現。這是JLS要求的。 – EJP

相關問題