【问题标题】:why garbage collector does not destroying any object as a value in WeakHashMap which doesn't have any refrence?为什么垃圾收集器不销毁任何对象作为 WeakHashMap 中没有任何引用的值?
【发布时间】:2016-05-05 10:14:47
【问题描述】:

在下面的示例中,如果垃圾收集器用作weakHashMap 中的键,则垃圾收集器正在销毁一个无用(引用较少)的对象,这没关系.. 但是如果有任何无用的对象作为值,那么垃圾收集器为什么不销毁该对象。 .

     public class WeakHashMapDemo {
    public static void main(String[] args) throws InterruptedException{
        WeakHashMap whs=new WeakHashMap();
        Temp t=new Temp();
        Temp t1=new Temp();
        Integer x=new Integer(5);
        Integer y=6;
        whs.put(t,"hemant");
        whs.put("hemant", t1);
        whs.put(x,"durga");
        whs.put(y,"bacon");
        System.out.println(whs);
        t=null;
        t1=null;
        x=null;
        y=null;
        System.gc();
        Thread.sleep(2000);
        System.out.println(whs);
    }
}   

临时类:-

class Temp{

    @Override
    public String toString() {
        return "temp"; //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalize() mrthod is called");

    }



}  

输出

  {hemant=temp, 6=bacon, 5=durga, temp=hemant}
  finalize() mrthod is called
  {hemant=temp, 6=bacon}  

根据我的输出应该是:-

  {hemant=temp, 6=bacon, 5=durga, temp=hemant}
  finalize() mrthod is called
  {hemant=null}  

【问题讨论】:

    标签: java garbage-collection weakhashmap


    【解决方案1】:

    WeakHashMap 被定义为具有弱键但不具有弱值:

    Map 接口的基于哈希表的实现,带有弱键。 WeakHashMap 中的条目将在其 key 时被自动删除 已不再正常使用。

    如果对键有任何引用,则键值对将继续存在于映射中。

    "Hemant" 仍然存在,因为它是字符串文字,所以在字符串池中,而6 将存在,因为它是一个小的整数文字,所以它在整数池中。

    分配给xt 的对象不存在,因为它们是使用new 关键字创建的,该关键字会创建一个新对象,然后将它们设置为null,从而删除对该对象的唯一引用.

    因此,由于仍然存在对 "Hemant"6 的引用,因此这些键及其值将保留在映射中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2013-10-18
      • 2012-04-20
      相关资源
      最近更新 更多