相信很多人对WeakHashMap并没有完全理解。

WeakHashMap 持有的弱引用的 Key。

1. 弱引用的概念:

  弱引用是用来描述非必需对象的,被弱引用关联的对象只能生存到下一次垃圾收集发生之前,当垃圾收集器工作时,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。

2. WeakHashMap中的弱引用

Key是如何被清除的?

  WeakHashMap中的清除Key的核心方法:

private void expungeStaleEntries() {
Entry<K,V> e;
while ( (e = (Entry<K,V>) queue.poll()) != null) {
int h = e.hash;
int i = indexFor(h, table.length); Entry<K,V> prev = table[i];
Entry<K,V> p = prev;
while (p != null) {
Entry<K,V> next = p.next;
if (p == e) {
if (prev == e)
table[i] = next;
else
prev.next = next;
e.next = null; // Help GC
e.value = null; // " "
size--;
break;
}
prev = p;
p = next;
}
}
}

  查看调用关系,可以看到几乎所有的方法都直接或间接的调用了该方法。但是查看WeakHashMap源码,并没有找到何时将Entry放入queue中。

  那么queue队列中的Entry是如何来的?

Key弱引用是如何关联的?

  毫无疑问,一定是在put元素的时候,key被设置为弱引用。

    public V put(K key, V value) {
K k = (K) maskNull(key);
int h = HashMap.hash(k.hashCode());
Entry[] tab = getTable();
int i = indexFor(h, tab.length); for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
if (h == e.hash && eq(k, e.get())) {
V oldValue = e.value;
if (value != oldValue)
e.value = value;
return oldValue;
}
}
modCount++;
Entry<K,V> e = tab[i];
tab[i] = new Entry<K,V>(k, value, queue, h, e); //创建一个新节点
if (++size >= threshold)
resize(tab.length * 2);
return null;
}

  其中的queue为:

    /**
* Reference queue for cleared WeakEntries
*/
private final ReferenceQueue<K> queue = new ReferenceQueue<K>();

再来看一下Entry<K,V>的声明及构造函数:

    private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {/**
* Creates new entry.
*/
Entry(K key, V value,
ReferenceQueue<K> queue,
int hash, Entry<K,V> next) {
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
}
}

  Entry<K,V>继承了WeakReference,并且在构造函数中将key 和 queue 提交给WeakReference,那么再来看一下WeakReference的构造函数:

public class WeakReference<T> extends Reference<T> {
  //....
public WeakReference(T referent, ReferenceQueue<? super T> q) {
  super(referent, q);
}
}
public abstract class Reference<T> {

  private static Reference pending = null;
  Reference(T referent, ReferenceQueue<? super T> queue) {
  this.referent = referent;
  this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
  }
}

  现在答案就在Reference中。

打开Reference源码,可以看到一个静态块:

  static {
  ThreadGroup tg = Thread.currentThread().getThreadGroup();
  for (ThreadGroup tgn = tg;tgn != null;tg = tgn, tgn = tg.getParent());
  Thread handler = new ReferenceHandler(tg, "Reference Handler");
  /* If there were a special system-only priority greater than
  * MAX_PRIORITY, it would be used here
  */
   handler.setPriority(Thread.MAX_PRIORITY);
   handler.setDaemon(true);
   handler.start();
}

  其中for循环直到 获取到 JVM 线程组,使用JVM线程执行ReferenceHandler。

  ReferenceHandler是Reference的内部类:

 private static class ReferenceHandler extends Thread {

    ReferenceHandler(ThreadGroup g, String name) {
super(g, name);
} public void run() {
for (;;) {
   Reference r;
  synchronized (lock) {
  if (pending != null) {
    r = pending;
    Reference rn = r.next;
    pending = (rn == r) ? null : rn;
    r.next = r;
  } else {
    try {
    lock.wait();
    } catch (InterruptedException x) { }
    continue;
  }
  }    // Fast path for cleaners
  if (r instanceof Cleaner) {
  ((Cleaner)r).clean();
  continue;
   }    ReferenceQueue q = r.queue;
   if (q != ReferenceQueue.NULL) q.enqueue(r);
}
}
}

  现在我们应该已经清楚了,守护线程一直执行入队操作,将key关联的Entry<K,V>放入queue中。

  但是将key放入queue中需要前提条件: pending

  这个pending是在垃圾回收的时候,JVM计算对象key的可达性后,发现没有该key对象的引用,那么就会把该对象关联的Entry<K,V>添加到pending中,

所以每次垃圾回收时发现弱引用对象没有被引用时,就会将该对象放入待清除队列中,最后由应用程序来完成清除,WeakHashMap中就负责由

方法expungeStaleEntries()来完成清除。

例子: 

   @Test
public void weakHashMap(){
Map<String, String> weak = new WeakHashMap<String, String>();
weak.put(new String("1"), "1");
weak.put(new String("2"), "2");
weak.put(new String("3"), "3");
weak.put(new String("4"), "4");
weak.put(new String("5"), "5");
weak.put(new String("6"), "6");
System.out.println(weak.size());
System.gc(); //手动触发 Full GC
try {
Thread.sleep(50); //我的测试中发现必须sleep一下才能看到不一样的结果
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(weak.size());
}

  上面的例子是可以正确的,但是下面的就有问题了:

   @Test
public void weakHashMap(){
Map<String, String> weak = new WeakHashMap<String, String>();
weak.put("1", "1");
weak.put("2", "2");
weak.put("3", "3");
weak.put("4", "4");
weak.put("5", "5");
weak.put("6", "6");
System.out.println(weak.size());
System.gc();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(weak.size());
}

  无论sleep多长时间,引用也不会被清除。这涉及到String在JVM中的工作方式了,这个问题留给读者自己思考。

WeakHashMap<K,V> 中的弱引用的更多相关文章

  1. 理解Java中的弱引用(Weak Reference)

    本篇文章尝试从What.Why.How这三个角度来探索Java中的弱引用,理解Java中弱引用的定义.基本使用场景和使用方法.由于个人水平有限,叙述中难免存在不准确或是不清晰的地方,希望大家可以指出, ...

  2. C# 中的弱引用 WeakReference

    C#中的弱引用(WeakReference)   我们平常用的都是对象的强引用,如果有强引用存在,GC是不会回收对象的.我们能不能同时保持对对象的引用,而又可以让GC需要的时候回收这个对象呢?.NET ...

  3. 简单说说.Net中的弱引用

    弱引用是什么? 要搞清楚什么是弱引用,我们需要先知道强引用是什么.强引用并不是什么深奥的概念,其实我们平时所使用的.Net引用就是强引用.例如: Cat kitty = new Cat(); 变量ki ...

  4. Java中的弱引用

    Strong references StringBuffer buffer = new StringBuffer(); 普通的对象创建都是这种类型,只要buffer还存在,对象就不会被GC回收.同时也 ...

  5. .NET中的弱引用

    弱引用是什么? 要搞清楚什么是弱引用,我们需要先知道强引用是什么.强引用并不是什么深奥的概念,其实我们平时所使用的.Net引用就是强引用.例如: Cat cat = new Cat(); 变量cat就 ...

  6. 关于C#中的弱引用

    本文前部分来自:http://www.cnblogs.com/mokey/archive/2011/11/24/2261605.html 分割线后为作者补充部分. 一:什么是弱引用 了解弱引用之前,先 ...

  7. Android开发过程中使用弱引用解决内存泄露的习惯

    Java虽然有垃圾回收,但是仍然存在内存泄露,比如静态变量.缓存或其他长生命周期的对象引用了其他对象,这些被引用的对象就会长期不能被GC释放,导致内存泄露. 弱引用(WeakReference)是解决 ...

  8. C#中的弱引用(WeakReference)

    我们平常用的都是对象的强引用,如果有强引用存在,GC是不会回收对象的.我们能不能同时保持对对象的引用,而又可以让GC需要的时候回收这个对象呢?.NET中提供了WeakReference来实现.弱引用可 ...

  9. Map<K, V> 中k,v如果为null就转换

    Set<String> set = map.keySet(); if(set != null && !set.isEmpty()) { for(String key : s ...

随机推荐

  1. js 数组对象的操作方法

    在jquery中处理JSON数组的情况中遍历用到的比较多,但是用添加移除这些好像不是太多. 今天试过json[i].remove(),json.remove(i)之后都不行,看网页的DOM对象中好像J ...

  2. 57.1拓展之纯 CSS 创作黑暗中的眼睛和嘴巴

    效果地址:https://scrimba.com/c/cJ8NPpU2 HTML code: <div class="eyes"> <span class=&qu ...

  3. mybatis-spring 集成

    http://www.mybatis.org/spring/zh/index.html http://www.mybatis.org/mybatis-3/zh/java-api.html 编程API: ...

  4. 二级VB备考中

    今天安装了一个VB软件,二级备考中,每天一套牌卷子. 在Html5中 align 与valign改变了属性 vertial-align  是垂直方向的改变 面对网站首页的建立需要首先画好一份区域设计图 ...

  5. 将Oracle中的表结构导出到word

    语句如下: SELECT t1.Table_Name AS "表名称",t3.comments AS "表说明", t1.Column_Name AS &quo ...

  6. 使用spring validation完成数据后端校验

    前言 数据的校验是交互式网站一个不可或缺的功能,前端的js校验可以涵盖大部分的校验职责,如用户名唯一性,生日格式,邮箱格式校验等等常用的校验.但是为了避免用户绕过浏览器,使用http工具直接向后端请求 ...

  7. vue下载和上传excle数据文件,解析excel文件数据并存在数据库中

    下载: VUE: window.open("xxxx/downloadOldTaskDataFile.do_", "_blank"); JAVA: /** * ...

  8. 机器学习进阶-案例实战-停车场车位识别-keras预测是否停车站有车

    import numpy import os from keras import applications from keras.preprocessing.image import ImageDat ...

  9. mybatis 异常和注意

    1.  Could not set parameters for mapping like语句出错,因将%%写入到mapper.xml中导致,将%%随同参数一并传入. 例:String userNam ...

  10. Windows下MongoDB安装配置

    一.安装 官网下载,一般选择community server版本下载,如果是企业可以选择enterprise版本,个人使用的话community就可以了,附上链接:https://www.mongod ...