码迷,mamicode.com
首页 > 其他好文 > 详细

WeakHashMap学习(一) —— Difference between HashMap and WeakHashMap

时间:2015-12-23 12:34:53      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

WeakHashMap is an implementation of Map interface where the memory of the value object can be reclaimed by Grabage Collector if the corresponding key is no longer referred by any section of program. This is different from HashMap where the value object remain in HashMap even if key is no longer referred We need to explicitly call remove() method on HashMap object to remove the value so that it can be ready to be reclaimed(Provided no other section of program refers to that value object). Calling remove() is an extra overhead.

理解:当WeakHashMap中的value(对象)不在被key(引用,可能是变为空)指向,那么这个value对象就会被删除,而HashMap中这个value对象则会一直被保存,需要调用remove函数来将其进行回收。

Here is a simple program which demonstrate the difference:-

 

import java.util.HashMap;

import java.util.Map;

import java.util.WeakHashMap;

public class WeakMap {

public static void main(String[] args) {

Map weak = new WeakHashMap();

Map map = new HashMap();

{

    String weakkey = new String("weakkey");

    weak.put(weakkey,new Object());

    String key = new String("key");

    map.put(key, new Object());

    weakkey = null;

    key = null;

}

    System.gc();

}

}

 

Here we create an instance of WeakHashMap and HashMap, populate one value and finally make key to null.  Program calls System.gc() to run garbage collector. Lets see what is the output after running the garbage collector.

Next two image shows the content of two Maps before running GC:-

First two image shows the content of weak and map instance before the GC is called.  weak reference contains a key “weakkey” and corresponding value. Similarly map contains a key “key” and value. Nothing unusual as such.

Next 2 slides contains the value after GC is called. You can see that there is no entry in weak Map. reason is that as we make weakkey as null the corresponsing value is no longer referred from any part of program and eligible for GC. But in case of map  key and value remain seated present in map.

理解:WeakHashMap中,当我们将弱引用变为空时,相应的value对象就可以被GC掉。

WeakHashMap学习(一) —— Difference between HashMap and WeakHashMap

标签:

原文地址:http://www.cnblogs.com/Guoyutian/p/5069319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!