HashMap和Hashtable探究

来源:互联网 发布:僵尸变脸软件 编辑:程序博客网 时间:2024/06/03 22:27

java.util包中有一个Map接口,此接口主要有四个常用的实现类,分别是HashMap、Hashtable、LinkedHashMap和TreeMap。其中Hashtable显得有点异样,本文主要探究HashMap和Hashtable的不同。

HashMap和Hashtable?

继承不同

这里写图片描述
从上图可以看出,HashMap继承自Map接口的一个实现类AbstractMap,而Hashtable则继承自Dictionary,同时实现了Map接口。

是否允许空值?

  • HashMap允许一个键为null,允许多个值为null。
  • Hashtable的键和值都必须非空
    HashMap中key若为null则其的hash值为0,因为不能有重复的hash码,所以只能有一条记录的键为null,值则没有要求。而hashtable中,当需要key的hash码时直接用key.hashcode()来返回hash码,所以key不能为null。值不能为null是因为在put的时候就过滤了,hash map没有过滤值为null的元素。
    具体来说:

HashMap中计算key的hash值:

static final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);    }

HashMap的put函数:

 public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);    }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node<K,V>[] tab; Node<K,V> p; int n, i;        if ((tab = table) == null || (n = tab.length) == 0)            n = (tab = resize()).length;        if ((p = tab[i = (n - 1) & hash]) == null)            tab[i] = newNode(hash, key, value, null);        else {        //出于篇幅考虑省略putVal的余下代码

可以看到,HashMap并没有为添加的Map做非空的过滤。而ConcurrentHashMap以及Hashtable都做了此过滤。
ConcurrentHashMap的put方法:

  public V put(K key, V value) {        return putVal(key, value, false);    }    /** Implementation for put and putIfAbsent */    final V putVal(K key, V value, boolean onlyIfAbsent) {        if (key == null || value == null) throw new NullPointerException();        int hash = spread(key.hashCode());        int binCount = 0;        //出于篇幅考虑省略余下代码

Hashtable的put方法:

 public synchronized V put(K key, V value) {        // Make sure the value is not null        if (value == null) {            throw new NullPointerException();        }        // Makes sure the key is not already in the hashtable.        Entry<?,?> tab[] = table;        int hash = key.hashCode();        int index = (hash & 0x7FFFFFFF) % tab.length;        //出于篇幅考虑省略余下代码

可以看到hashtable中计算hash值时直接用key.hashcode()。key若为空则抛出空指针异常。故而,Hashtable中键和值都不能为null。

线程安全?

HashMap是线程不安全的,Hashtable是线程安全的,但并发性不如ConcurrentHashMap,因为ConcurrentHashMap引入了分段锁
具体来说是这样的,看看Hashtable中其中一个方法:

public synchronized V getOrDefault(Object key, V defaultValue) {        V result = get(key);        return (null == result) ? defaultValue : result;    }

Hashtable简单粗暴地使用了synchronized关键字来保证线程安全。这种策略在并发条件下显得很低效,因为当一个线程调用Hashtable的put时,其他线程不但不能使用put,也不能使用get来获取元素。也就是所有的线程竞争同一把锁,这在并发情况下会造成严重的阻塞。
ConcurrentHashMap是怎么做的?
ConcurrentHashMap将数据分成一段一段地存储,然后每一段分一把锁,当一个线程占用锁访问一段数据时,其他线程仍可访问其他数据段,从而大大提高了并发效率。
接下来会写一篇博文探究ConcurrentHashMap的具体实现,里面会涉及数据分段的内容。

完。

0 0