为了分析ConcurrentHashMap,决定先分析一下Hashtable,两者都是线程安全的,必然会有不同的区别,Hashtable和HashMap也有很大的区别。
我们先来看看Hashtable吧。
成员变量:
//存储单链表表头的数组,和HashMap中类似 private transient Entry[] table; //Hashtable中实际元素的数量 private transient int count; //Hashtable的临界值(容量* 加载因子). private int threshold; //加载因子 private float loadFactor; //修改次数,提供fast-fail机制 private transient int modCount = 0; //Hashtable的版本号 private static final long serialVersionUID = 1421746759512286392L;
构造函数:
//构造一个新的Hashtable,有指定的初始容量和加载因子。注意到没有设置Hashtable的最大容量是多少。 public Hashtable(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal Load: "+loadFactor); if (initialCapacity==0) initialCapacity = 1; this.loadFactor = loadFactor; table = new Entry[initialCapacity]; threshold = (int)(initialCapacity * loadFactor); } //指定初始容量,和HashMap一样,加载因子是0.75 public Hashtable(int initialCapacity) { this(initialCapacity, 0.75f); } //默认的无参构造,发现默认容量大小是11 public Hashtable() { this(11, 0.75f); } //将指定Map集合传递给Hashtable,默认加载因子是0.75 public Hashtable(Map<? extends K, ? extends V> t) { this(Math.max(2*t.size(), 11), 0.75f); putAll(t); }
Hashtable解决冲突的单链表:
private static class Entry<K,V> implements Map.Entry<K,V> { int hash; K key; V value; Entry<K,V> next; protected Entry(int hash, K key, V value, Entry<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } //复制,为了Hashtable的克隆,后面会看到 protected Object clone() { return new Entry<K,V>(hash, key, value, (next==null ? null : (Entry<K,V>) next.clone())); } // Map.Entry Ops public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { //如果为空抛出异常 if (value == null) throw new NullPointerException(); V oldValue = this.value; this.value = value; //设置后返回旧值 return oldValue; } //若key和value都相等才返回true public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; return (key==null ? e.getKey()==null : key.equals(e.getKey())) && (value==null ? e.getValue()==null : value.equals(e.getValue())); } //哈希值为键的哈希值异或值的哈希值 public int hashCode() { return hash ^ (value==null ? 0 : value.hashCode()); } public String toString() { return key.toString()+"="+value.toString(); } }
其他方法:
//使用的同步函数进行控制 public synchronized int size() { return count; } //判断是否为空 public synchronized boolean isEmpty() { return count == 0; } //返回所有key的枚举对象 public synchronized Enumeration<K> keys() { return this.<K>getEnumeration(KEYS); } //返回所有value的枚举对象 public synchronized Enumeration<V> elements() { return this.<V>getEnumeration(VALUES); } //判断Hashtable中是否包含指定的对象 public synchronized boolean contains(Object value) { //如果指定的对象时null,则抛出异常,说明Hashtable中不支持null键 if (value == null) { throw new NullPointerException(); } //双重for遍历寻找,从后向前遍历数组,逐一遍历链表 Entry tab[] = table; for (int i = tab.length ; i-- > 0 ;) { for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) { if (e.value.equals(value)) { return true; } } } return false; } //与上面一样,因为实现了Map接口,所以需要实现此方法 public boolean containsValue(Object value) { return contains(value); } //判断是否包含于指定key相同的键 public synchronized boolean containsKey(Object key) { Entry tab[] = table; int hash = key.hashCode(); //这里的hash值直接采用key的hash值 //数组中的索引值计算方法不同,此处与上0x7FFFFFFF是为了将负数(hashCode有可能是负数)转为正数 //然后对数组长度取模 int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return true; } } return false; } //提取与指定key相同的键,若没有返回null public synchronized V get(Object key) { Entry tab[] = table; int hash = key.hashCode();//取出key的hash值 int index = (hash & 0x7FFFFFFF) % tab.length; //计算索引 //搜索 for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return e.value; } } return null; } //调整Hashtable的大小 protected void rehash() { int oldCapacity = table.length; Entry[] oldMap = table; //直接调整为原来的大小的2倍,至于为什么加1,在put某一个数的时候,发现需要调整,那么调整完后,还要把这个数给添加进去,1就是给那个数留的空间。 int newCapacity = oldCapacity * 2 + 1; Entry[] newMap = new Entry[newCapacity]; modCount++; //修改次数加1 threshold = (int)(newCapacity * loadFactor); //重新设置临界值 table = newMap; //重新赋引用 //将旧值全部复制到新的Hashtable中 for (int i = oldCapacity ; i-- > 0 ;) { for (Entry<K,V> old = oldMap[i] ; old != null ; ) { Entry<K,V> e = old; old = old.next; int index = (e.hash & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } } //往里面put键值对 public synchronized V put(K key, V value) { //同样,如果是null则抛出异常 if (value == null) { throw new NullPointerException(); } // 如果key存在当前的Hashtable中,用对应的旧值替换新值 Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { V old = e.value; e.value = value; return old; } } modCount++; //修改次数加1 //如果Hashtable中总数量大于临界值 if (count >= threshold) { //扩容 rehash(); tab = table; index = (hash & 0x7FFFFFFF) % tab.length; } // 将旧值放到新值的后面,新值放到头结点 Entry<K,V> e = tab[index]; tab[index] = new Entry<K,V>(hash, key, value, e); count++; return null; } //移除指定key键的元素 public synchronized V remove(Object key) { Entry tab[] = table; int hash = key.hashCode(); //获取Hash值 int index = (hash & 0x7FFFFFFF) % tab.length;//获取索引 for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { modCount++; if (prev != null) { prev.next = e.next; } else { //如果删除头结点,将下一个直接赋给数组 tab[index] = e.next; } count--; V oldValue = e.value; e.value = null; return oldValue; } } return null; } //将指定Map集合中的元素全部放入Hashtable中 public synchronized void putAll(Map<? extends K, ? extends V> t) { for (Map.Entry<? extends K, ? extends V> e : t.entrySet()) put(e.getKey(), e.getValue()); } //清空Hashtable public synchronized void clear() { Entry tab[] = table; modCount++; for (int index = tab.length; --index >= 0; ) tab[index] = null; //置为null count = 0; } //克隆一个Hashtable,浅克隆 public synchronized Object clone() { try { Hashtable<K,V> t = (Hashtable<K,V>) super.clone(); t.table = new Entry[table.length]; for (int i = table.length ; i-- > 0 ; ) { t.table[i] = (table[i] != null) ? (Entry<K,V>) table[i].clone() : null; } t.keySet = null; t.entrySet = null; t.values = null; t.modCount = 0; return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } //重写的toString,而HashMap的是继承自AbstractMap,最后做判断的时候略微不一样 //HashMap是直接用迭代器判断hashNext,而Hashtable是判断个数 public synchronized String toString() { int max = size() - 1; if (max == -1) return "{}"; StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<K,V>> it = entrySet().iterator(); sb.append('{'); for (int i = 0; ; i++) { Map.Entry<K,V> e = it.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key.toString()); sb.append('='); sb.append(value == this ? "(this Map)" : value.toString()); if (i == max) return sb.append('}').toString(); sb.append(", "); } }
先看三个常量:
// 可以看到0是键,1是值,2是键值对 private static final int KEYS = 0; private static final int VALUES = 1; private static final int ENTRIES = 2;
遍历方法:
//返回Hashtable的枚举类对象,传入的参数是类型,表示是键还是值,还是键值 private <T> Enumeration<T> getEnumeration(int type) { if (count == 0) { return (Enumeration<T>)emptyEnumerator; } else { return new Enumerator<T>(type, false); } } //返回迭代器 private <T> Iterator<T> getIterator(int type) { if (count == 0) { return (Iterator<T>) emptyIterator; } else { return new Enumerator<T>(type, true); } } //Hashtable中所有键的集合 private transient volatile Set<K> keySet = null; //Hashtable中所有键值对的集合 private transient volatile Set<Map.Entry<K,V>> entrySet = null; private transient volatile Collection<V> values = null; //所有值的集合 //返回所有键的集合,调用Collections的synchronizedSet,这样就给keySet中的所有方法全部加上synchronized 实现同步 public Set<K> keySet() { if (keySet == null) keySet = Collections.synchronizedSet(new KeySet(), this); return keySet; } //定义的keySet类继承AbstractSet private class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return getIterator(KEYS); } public int size() { return count; } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { return Hashtable.this.remove(o) != null; } public void clear() { Hashtable.this.clear(); } } //返回Hashtable中的键值对集合,自动给 public Set<Map.Entry<K,V>> entrySet() { if (entrySet==null) entrySet = Collections.synchronizedSet(new EntrySet(), this); return entrySet; } //定义的EntrySet类 private class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return getIterator(ENTRIES); } public boolean add(Map.Entry<K,V> o) { return super.add(o); } //判断entrySet中是否包含指定的对象 // 同样要获取哈希值,计算按索引 public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; Object key = entry.getKey(); Entry[] tab = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; //查找Entry对象是否在entryset for (Entry e = tab[index]; e != null; e = e.next) if (e.hash==hash && e.equals(entry)) return true; return false; } //将存在的对象删除 public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; K key = entry.getKey(); Entry[] tab = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash==hash && e.equals(entry)) { modCount++; if (prev != null) prev.next = e.next; else tab[index] = e.next; count--; e.value = null; return true; } } return false; } public int size() { return count; } public void clear() { Hashtable.this.clear(); } } //返回Hashtable中所有值的集合,用synchronized修饰,保证其所有方法都是同步的 public Collection<V> values() { if (values==null) values = Collections.synchronizedCollection(new ValueCollection(), this); return values; } private class ValueCollection extends AbstractCollection<V> { public Iterator<V> iterator() { return getIterator(VALUES); } public int size() { return count; } public boolean contains(Object o) { return containsValue(o); } public void clear() { Hashtable.this.clear(); } } //依次遍历Hashtable的entrySet的集合 public synchronized boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map<K,V> t = (Map<K,V>) o; if (t.size() != size()) return false; try { Iterator<Map.Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) { Map.Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(t.get(key)==null && t.containsKey(key))) return false; } else { if (!value.equals(t.get(key))) return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } //这是hashCode的计算 public synchronized int hashCode() { int h = 0; //若Hashtable为空,或者加载因子小于0,则返回0 if (count == 0 || loadFactor < 0) return h; // Returns zero loadFactor = -loadFactor; // Mark hashCode computation in progress Entry[] tab = table; for (int i = 0; i < tab.length; i++) for (Entry e = tab[i]; e != null; e = e.next) //每个key的hash值和value的hash值异或相加 h += e.key.hashCode() ^ e.value.hashCode(); loadFactor = -loadFactor; // Mark hashCode computation complete return h; } //序列化,将Hashtable的实际长度,哈希数组的长度,以及每个链表的值都写入 private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { // Write out the length, threshold, loadfactor s.defaultWriteObject(); // Write out length, count of elements and then the key/value objects s.writeInt(table.length); s.writeInt(count); for (int index = table.length-1; index >= 0; index--) { Entry entry = table[index]; while (entry != null) { s.writeObject(entry.key); s.writeObject(entry.value); entry = entry.next; } } } //将流中的数据依次读取出 private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the length, threshold, and loadfactor s.defaultReadObject(); // Read the original length of the array and number of elements int origlength = s.readInt(); int elements = s.readInt(); // Compute new size with a bit of room 5% to grow but // no larger than the original size. Make the length // odd if it's large enough, this helps distribute the entries. // Guard against the length ending up zero, that's not valid. int length = (int)(elements * loadFactor) + (elements / 20) + 3; if (length > elements && (length & 1) == 0) length--; if (origlength > 0 && length > origlength) length = origlength; Entry[] table = new Entry[length]; count = 0; // Read the number of elements and then all the key/value objects for (; elements > 0; elements--) { K key = (K)s.readObject(); V value = (V)s.readObject(); // synch could be eliminated for performance reconstitutionPut(table, key, value); } this.table = table; }
Hashtable中的枚举类:
//给Hashtable提供了枚举遍历和迭代器遍历的好处 private class Enumerator<T> implements Enumeration<T>, Iterator<T> { Entry[] table = Hashtable.this.table; int index = table.length; Entry<K,V> entry = null; Entry<K,V> lastReturned = null; int type; //代表是迭代器还是枚举类,true代表迭代器,false代表枚举类 boolean iterator; //提供fast-fail机制 protected int expectedModCount = modCount; Enumerator(int type, boolean iterator) { this.type = type; this.iterator = iterator; } //向前遍历,是否还有别的数,直到找到null为止 public boolean hasMoreElements() { Entry<K,V> e = entry; int i = index; Entry[] t = table; /* Use locals for faster loop iteration */ while (e == null && i > 0) { e = t[--i]; } entry = e; index = i; return e != null; } public T nextElement() { Entry<K,V> et = entry; int i = index; Entry[] t = table; /* Use locals for faster loop iteration */ while (et == null && i > 0) { et = t[--i]; } entry = et; index = i; if (et != null) { Entry<K,V> e = lastReturned = entry; entry = e.next; return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e); } throw new NoSuchElementException("Hashtable Enumerator"); } // 迭代器的方法 public boolean hasNext() { return hasMoreElements(); } public T next() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); return nextElement(); } //修改动作要加锁 public void remove() { if (!iterator) throw new UnsupportedOperationException(); if (lastReturned == null) throw new IllegalStateException("Hashtable Enumerator"); if (modCount != expectedModCount) throw new ConcurrentModificationException(); synchronized(Hashtable.this) { Entry[] tab = Hashtable.this.table; int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length; //首先找到索引 for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e == lastReturned) { modCount++; expectedModCount++; if (prev == null) tab[index] = e.next; else prev.next = e.next; count--; lastReturned = null; return; } } throw new ConcurrentModificationException(); } } } //创建一个空的枚举对象 private static Enumeration emptyEnumerator = new EmptyEnumerator(); //创建一个空的迭代器对象 private static Iterator emptyIterator = new EmptyIterator(); //如果Hashtable大小为0,但是还要用枚举遍历,就返回一个空的枚举对象 private static class EmptyEnumerator implements Enumeration<Object> { EmptyEnumerator() { } public boolean hasMoreElements() { return false; } public Object nextElement() { throw new NoSuchElementException("Hashtable Enumerator"); } } //<span style="font-family: 宋体;">如果Hashtable大小为0,但是还要用迭代器遍历,就返回一个空的迭代器对象</span> private static class EmptyIterator implements Iterator<Object> { EmptyIterator() { } public boolean hasNext() { return false; } public Object next() { throw new NoSuchElementException("Hashtable Iterator"); } public void remove() { throw new IllegalStateException("Hashtable Iterator"); } }
总结:
首先我们可以看到Hashtable中的方法都加了synchronized修饰,这就保证了线程的安全性,但是这在一定程度上也降低了效率,没有HashMap的效率高。
HashMap和Hashtable的几点区别:
1、在指定参数构造函数时Hashtable如果指定的参数大于2的30次方,则不会替换;而HashMap则会用2的30次方替换。当然,不出意外的话,两个都会堆溢出。
2、HashMap的默认容量大小是16,而Hashtable的是11
3、Hashtable中不支持<null,null>,会抛出空指针异常,但是HashMap中支持
4、增加、删除、查询等一系列操作,Hashtable会直接采用key的hash值,而HashMap则是重新计算Hash值
5、HashMap中的遍历方式只支持迭代器;Hashtable中遍历方式有迭代器和枚举。
6、二者在扩容时采用的策略不一样:HashMap中在扩容时是先将值添加到链表上,然后判断下一次是否需要扩容;而Hashtable是在添加的时候
决定是否需要扩容,所以需要多分出来一个元素的空间。
7、Hashtable继承自Dictionary,而HashMap继承自AbstractMap。
......
如果要从源码上说区别,感觉是说不完了,点到为止吧。
若有遗漏重要的,还请大家指教。
版权声明:本文为博主原创文章,转载请注明出处。
时间: 2024-10-05 05:58:27