Collection arrangement

1. Implementation of the map interface

 

 The biggest difference between these two classes is:
(1) Hashtable is thread-safe, its methods are synchronized and can be used directly in a multi-threaded environment.
(2) HashMap is not thread-safe. In a multithreaded environment, synchronization mechanisms need to be implemented manually.

1.1 hashmap 

Basic properties:

 

   /** Default initialization size
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

   /** Load factor for scaling
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

   /** table original value
     * An empty table instance to share when the table is not inflated.
     */
    static final Entry<?,?>[] EMPTY_TABLE = {};

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
 

 

put(K, V) implementation process:

 

public V put(K key, V value) {
        //Initialize map size
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        // handle key as null, HashMap allows key and value to be null
        if (key == null)
            return putForNullKey(value);
        // get the hash code of the key
        int hash = hash(key);
        // Calculate bucketIndex by hash code
        int i = indexFor(hash, table.length);
         // Take the element at the bucketIndex position, and loop the singly linked list to determine whether the key already exists
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            // when the hash codes are the same and the objects are the same
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                 //hashcode collides, the new value replaces the old value, and returns the old value  
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        // When the key does not exist, add a new element
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

    /**
     * add entry
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        // determine whether the threshold is exceeded
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        //add entry
        createEntry(hash, key, value, bucketIndex);
    }

    /**
     * Like addEntry except that this version is used when creating entries
     * as part of Map construction or "pseudo-construction" (cloning,
     * deserialization).  This version needn't worry about resizing the table.
     *
     * Subclass overrides this to alter the behavior of HashMap(Map),
     * clone, and readObject.
     */
    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }
   Hashmap flow chart:    1.2 hashTable

(1) It is a two-dimensional array containing a one-way chain. The table array is Entry<K,V> storage, entry object;

 (2) The placed value cannot be empty;

 

 (3) Thread-safe, all methods are modified with synchronized;

/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key.equals(k))},
     * then this method returns {@code v}; otherwise it returns
     * {@code null}.  (There can be at most one such mapping.)
     *
     * @param key the key whose associated value is to be returned
     * @return the value to which the specified key is mapped, or
     *         {@code null} if this map contains no mapping for the key
     * @throws NullPointerException if the specified key is null
     * @see     #put(Object, Object)
     */
    public synchronized V get(Object key) {
        Entry tab[] = table;
        int hash = hash(key);
        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;
    }

/**
     * Maps the specified <code>key</code> to the specified
     * <code>value</code> in this hashtable. Neither the key nor the
     * value can be <code>null</code>. <p>
     *
     * The value can be retrieved by calling the <code>get</code> method
     * with a key that is equal to the original key.
     *
     * @param      key     the hashtable key
     * @param      value   the value
     * @return     the previous value of the specified key in this hashtable,
     *             or <code>null</code> if it did not have one
     * @exception  NullPointerException  if the key or value is
     *               <code>null</code>
     * @see     Object#equals(Object)
     * @see     #get(Object)
     */
    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 = hash(key);
        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++;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

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

        // Creates the new entry.
        Entry<K,V> e = tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
        return null;
    }

 

1.3. ConcurrentHashMap thread safety
As can be seen from the ConcurrentHashMap code, it introduces a concept of "segment lock", which can be understood as splitting a large Map into N small HashTables, and according to key.hashCode() to decide to put the key in the Which HashTable.
In ConcurrentHashMap, when the Map is divided into N segments, when put and get, it is now calculated according to key.hashCode() into which segment:
Weak consistency: http://ifeve.com/concurrenthashmap-weakly-consistent/
The main difference between ConcurrentHashMap and Hashtable is around the granularity of locks and how to lock, which can be simply understood as decomposing a large HashTable into multiple ones, forming lock separation.
As can be seen from the ConcurrentHashMap code, it introduces a concept of "segment lock", which can be understood as splitting a large Map into N small HashTables, and according to key.hashCode() to decide to put the key in the Which HashTable. In ConcurrentHashMap, when the Map is divided into N segments, put and get, it is now calculated according to key.hashCode() which segment is placed in: Weak consistency: http://ifeve.com/concurrenthashmap-weakly -consistent/ The main difference between ConcurrentHashMap and Hashtable is around the granularity of locks and how to lock them, which can be simply understood as decomposing a large HashTable into multiple ones, forming lock separation.    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326485591&siteId=291194637