手写ConcurrentHashMap

分析了jdk1.7和1.8的ConcurrentHashMap源码之后,了解它的思想 尝试着自己手写ConcurrentHashMap

package com.shanheyongmu.map;

import java.util.Hashtable;

/**
 * 手写ConcurrentHashMap
 * @param <K>
 * @param <V>
 */
public class ExtConcurrentHashMap<K,V> {
    /**
     * segments
     */
    private Hashtable<K,V>[] segments;

    public ExtConcurrentHashMap(){
        segments = new Hashtable[16];
        //注意懒加载形式
    }

    public void put(K k,V v){
        //第一次计算index 计算key存放哪个hashTable
        int segmentIndex = k.hashCode() & (segments.length -1);
        Hashtable<K, V> segment = segments[segmentIndex];
        if(segment==null){
           segment = new Hashtable<>();
        }
        segment.put(k,v);
        //注意这里需要赋值否则循环打印会为空
        segments[segmentIndex] = segment;
    }

    public V get(K k){
        int segmentIndex = k.hashCode() & (segments.length -1);
        Hashtable<K, V> segment = segments[segmentIndex];
        if(segment!=null){
           return segment.get(k);
        }
        return null;
    }

    public static void main(String[] args) {
        ExtConcurrentHashMap<String,String> concurrentHashMap = new ExtConcurrentHashMap<>();
        for (int i = 0; i < 10; i++) {
            concurrentHashMap.put(i+"",i+"");
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(concurrentHashMap.get(i+ ""));
        }
    }
}

 

posted @ 2023-02-05 13:41  山河永慕~  阅读(29)  评论(0编辑  收藏  举报