Jdk source code reading-"LinkedHashMap class source code interpretation

I. Overview

LinkedHashMap is because I saw it in the LruCache class of the mybatis cache source code. I was puzzled by it, so I followed it in and took a look. Therefore, the content of this article is only to solve

LruCache 中removeEldestEntry方法 最老的元素 是如何来的来展开说。

Because I want to know. In this LinkedHashMap. Where did the least visited data come from? I started to look at the code and do data debugging.

This is my test data

package com.llr.reflect.test;

import java.util.LinkedHashMap;

public class LinkedHashMapTest {
    public static void main(String[] args) {
        LinkedHashMap<Object,String> linkedHashMap= new LinkedHashMap<Object, String>(100, .75F, true) {
        };
        linkedHashMap.put("1","2");
        linkedHashMap.put("2","3");
        linkedHashMap.put("3","3");
        linkedHashMap.put("4","3");
        System.out.println(linkedHashMap.get("2"));
        System.out.println(linkedHashMap.get("1"));
        System.out.println(linkedHashMap.get("1"));
    }
}

This is a call to put. First, the put method of hashMap is called, and finally the afterNodeInsertion method of the subclass is called

When all 4 elements are put, the map looks like this

Now use System.out.println(linkedHashMap.get("2")); afterNodeAccess to reset and sort the chain

Now use System.out.println(linkedHashMap.get("1")); afterNodeAccess to reset and sort the chain

 

Two: It can be seen from the above test results. The afterNodeAccess in the LinkedHashMap class can reorder the chains and find the least used ones and put them in the first head attribute.

From this we know that the least accessed key is stored in the head, so in the next step, look at the relationship between this head and the removeEldestEntry method of the LinkedHashMap  .

Seeing that, head is assigned to first. And call the removeEldestEntry method, from this, we know.

removeEldestEntry方法的入参。就是最少被使用的键值对象。至于removeEldestEntry 方法在源码中返回的是false,那么我们可以重新这个方法,当满足我们什么条件的时候,我们就返回true。

I don't know if you can understand my expression. But I am really watery. I figured it out by myself. I believe you also understand. Hehe~

Three: Summary

When there is a problem, you need to think more. do not give up. do not give up!

 

 

Guess you like

Origin blog.csdn.net/lileronglilerong/article/details/113871176