HashTable源码解析

1.特点

HashTable可以键值对形式的数据,key和value 都不能为null。同时通过synchronized给put和get方法加锁,保证线程的安全。但是效率低。

原因:当多个线程执行put方法,put方法进行了加锁操作,这里锁住的实例对象,所以其他线程无法进行同步操作。

2.构造函数

/* The number of times this Hashtable has been structurally modified 
* Structural modifications are those that change the number of entries * in the Hashtable or otherwise modify its internal structure (e.g., 
* rehash). This field is used to make iterators on Collection-views of
* the Hashtable fail-fast. (See ConcurrentModificationException).
* 
* hashtable修改的次数 如:add remove clear 
*/
 private transient int modCount = 0;
//数组对象
private transient Entry<?,?>[] table;
//阈值,用于扩容
private int threshold;
//负载因子
private float loadFactor;

public Hashtable() {
// public Hashtable(int initialCapacity, float loadFactor)
    this(11, 0.75f);
}

3.put方法

给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;
        //key不能为null
        int hash = key.hashCode();
        //计算数据的index
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
        	//如果已经存在key,覆盖value
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }
		//添加新的entry
        addEntry(hash, key, value, index);
        return null;
    }


    private void addEntry(int hash, K key, V value, int index) {
        Entry<?,?> tab[] = table;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
        modCount++;
    }

4.get方法

 public synchronized V get(Object key) {
     Entry<?,?> tab[] = table;
     int hash = key.hashCode();
     int index = (hash & 0x7FFFFFFF) % tab.length;
     for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
         if ((e.hash == hash) && e.key.equals(key)) {
             return (V)e.value;
         }
     }
     return null;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值