zoukankan      html  css  js  c++  java
  • WeakHashMap的使用

    当我们需要大量使用 WeakReference 的时候,可以考虑使用 WeakHashMap

    在执行垃圾回收之前,WeakHashMap 和 普通的 HashMap 没有任何区别,但是一旦 执行垃圾回收,WeakHashMap 中的所有 key—value 对都会被清空。

    import java. util.WeakHashMap ;

    class Key{
        private String name ;    
        public Key (String name) {
             super();
             this.name = name;
        }
        
    }

    public class Main{
        public static void main (String[] args) throws Exception{
            WeakHashMap <Key, String> map = new WeakHashMap<Key , String>();
            for ( int i = 0 ; i < 10 ; i++) {
                map .put( new Key( i+""), "value"+i );
            }
            System .out. println(" 执行垃圾回收机制前: ");
            System .out. println(map );
            System .gc();
            //暂停当前线程使得后台垃圾回收线程得以运行
            Thread .sleep( 50);
            System .out. println(" 执行垃圾回收机制后: ");
            System .out. println(map );
            
        }
    }

    运行结果:

    执行垃圾回收机制前:
    {Key@42a57993=value9, Key@33909752=value6, Key@70dea4e=value4, Key@15db9742=value0, Key@5c647e05=value5, Key@7852e922=value2, Key@3d4eac69=value8, Key@55f96302=value7, Key@4e25154f=value3, Key@6d06d69c=value1}
    执行垃圾回收机制后:
    {}




  • 相关阅读:
    173. Binary Search Tree Iterator
    199. Binary Tree Right Side View
    230. Kth Smallest Element in a BST
    236. Lowest Common Ancestor of a Binary Tree
    337. House Robber III
    449. Serialize and Deserialize BST
    508. Most Frequent Subtree Sum
    513. Find Bottom Left Tree Value
    129. Sum Root to Leaf Numbers
    652. Find Duplicate Subtrees
  • 原文地址:https://www.cnblogs.com/ZhangJinkun/p/4531681.html
Copyright © 2011-2022 走看看