java之HashMap 与 WeakHashMap 一起被垃圾收集

telwanggs 阅读:178 2025-06-02 22:19:02 评论:0

据我了解,HashMap 不应该被垃圾回收,而 WeakHashMap 应该被垃圾回收,但是当我运行这段代码时,hashmap 和 weakhashmap 都被垃圾回收。

import java.util.HashMap; 
import java.util.WeakHashMap; 
public class WeakHashMapDemo { 
    public static void main(String[] args) { 
        HashMap<String,Temp> hashMap= new HashMap<>(); 
        hashMap.put("a", new Temp("hashmap")); 
        WeakHashMap<String,Temp> weakHashMap= new WeakHashMap<>(); 
        weakHashMap.put("a", new Temp("identity hashmap")); 
        hashMap= null; 
        weakHashMap= null; 
        System.gc(); 
        try { 
            Thread.sleep(5000); 
        }catch(InterruptedException interruptedException) { 
            interruptedException.printStackTrace(); 
        } 
        System.out.println(hashMap); 
        System.out.println(weakHashMap); 
    } 
} 
class Temp { 
    String name; 
    Temp(String name) { 
        this.name= name; 
    } 
    @Override 
    protected void finalize() throws Throwable { 
        super.finalize(); 
        System.out.println(name+":: Finalize Method Executed"); 
    } 
    @Override 
    public String toString() { 
        return this.name; 
    } 
} 

输出:

identity hashmap:: Finalize Method Executed 
hashmap:: Finalize Method Executed 
null 
null 

虽然仅使用 HashMap,但它不会被 GC 回收。

import java.util.HashMap; 
import java.util.WeakHashMap; 
public class WeakHashMapDemo { 
    public static void main(String[] args) { 
        HashMap<String,Temp> hashMap= new HashMap<>(); 
        hashMap.put("a", new Temp("hashmap")); 
        System.gc(); 
        try { 
            Thread.sleep(5000); 
        }catch(InterruptedException interruptedException) { 
            interruptedException.printStackTrace(); 
        } 
        System.out.println(hashMap); 
    } 
} 
class Temp { 
    String name; 
    Temp(String name) { 
        this.name= name; 
    } 
    @Override 
    protected void finalize() throws Throwable { 
        super.finalize(); 
        System.out.println(name+":: Finalize Method Executed"); 
    } 
    @Override 
    public String toString() { 
        return this.name; 
    } 
} 

输出:

{a=hashmap} 

请您参考如下方法:

首先不要使用 finalize - 它已被弃用,有更好的方法来清理你自己并且 SO 充满了这样的帖子(ReferenceQueueSoftReferences 就是其中之一)。

然后不要使用内部缓存的对象作为 WeakHashMap 中的键(String 就是这样)。

最后一点是,这与WeakHashMap无关,这是Objects的基本活力。在您的第一个示例中,您显式将引用设置为 null,因此它们会被 GC 清除,而在您的第二个示例中则不会,并通过System.out.println(hashMap);;因此它不会被收集。


标签:java
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号