HashTable -- thread security hash, hashtable thread

Source: Internet
Author: User
Tags rehash

HashTable -- thread security hash, hashtable thread


■ Important global variables

// The hash table data. // The underlying layer maintains an Entry (key-Value Pair) array private transient Entry <K, V> [] table;
// The total number of entries in the hash table. // The total number of elements, equivalent to the sizeprivate transient int count of HashMap;
// The load factor for the hashtable. // load factor private float loadFactor;
/*** The table is rehashed when its size exceeds this threshold. * (The value of this field is (int) (capacity * loadFactor ).) * rehash */private int threshold when the threshold is exceeded; /*** 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 ). * modCount + 1 during structural changes, used for the time-consuming fail-fast mechanism */private transient int modCount = 0


■ Constructor

/*** Constructs a new, empty hashtable with the specified initial * capacity and the specified load factor. */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 (initialCapacit Y = 0) initialCapacity = 1; // when the cap is 0, the default value is 1 this. loadFactor = loadFactor; table = new Entry <?,?> [InitialCapacity]; threshold = (int) Math. min (initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);}/*** Constructs a new, empty hashtable with a default initial capacity (11) * and load factor (0.75 ). * Capacity 11, load factor 0.75 */public Hashtable () {this (11, 0.75f );}


■ Main methods

-Put (K key, V value)

Public synchronized V put (K key, V value) {// Make sure the value is not null, in HashMap, if (value = null) {throw new NullPointerException ();} // Makes sure the key is not already in the hashtable. // ensure that the key is not in hashtable. // first, calculate the hash value of the key using the hash method, calculate the index value, and determine its position in table []. // second, iterate the linked list at the index position. If the linked list at the position has the same key, replace the value and return the old value Entry tab [] = table; int hash = hash (key); // calculate Subscript. Here the % method is used, and the performance is far less than the bit operation of HashMap (this is one of the reasons why HashTable is not recommended) int index = (hash & 0x7FFFFFFF) % tab. length; for (Entry <K, V> e = tab [index]; e! = Null; e = e. next) {// use equals for comparison directly, while HashMap has an additional layer of address comparison '(k = e. key) = key | key. equals (k) 'if (e. hash = hash) & e. key. equals (key) {V old = e. value; e. value = value; return old ;}}
// ModCount count + 1 modCount + + for structural change operations; // select the Add addEntry Method for HashMap to encapsulate the logic if (count> = threshold) {// Rehash the table if the threshold is exceeded // if the threshold value is exceeded, rehash (); tab = table; hash = hash (key ); index = (hash & 0x7FFFFFFF) % tab. length;} // Creates the new entry. // Insert the value and return null Entry <K, V> e = tab [index]; // create a new Entry node, insert the new Entry into the index position of Hashtable, and set e to the next element of the new Entry, tab [index] = new Entry <> (hash, key, value, e ); // size ++ count ++; return null ;}

-Get (Object key)

Public synchronized V get (Object key) {Entry tab [] = table; // temporary copy to ensure the timeliness of data. 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 ;}

■ HashTable Traversal

/*** Created by roman on. * [2017 java's day] */public class ListHashTableTest {public static void main (String [] args) {Hashtable <String, Object> hb = new Hashtable <String, object> (); hb. put ("1", "Java"); hb. put ("flag", true); hb. put ("age", 44); Iterator iterator = hb. keySet (). iterator (); iterator. forEachRemaining (value-> System. out. println (hb. get (value); // lamda used }}


■ HashTable VS HashMap

  • HashTable is based on the Dictionary class, while HashMap is based on AbstractMap. Dictionary is an abstract parent class of any class that maps keys to corresponding values. AbstractMap is implemented based on the Map interface to minimize the work required to implement this interface.
  • The key and value of HashMap can both be null, while the key and value of Hashtable cannot be null. When HashMap encounters a null key, it calls the putForNullKey method for processing (uniformly placed in the table [0] location), but does not process the value. If Hashtable encounters null, it returns NullPointerException directly.
  • The Hashtable method is synchronous, while the HashMap method is not. Almost all public methods in Hashtable are synchronized, and some methods are implemented internally through the synchronized code block.
  • HashTable is inferior to HashMap due to the use of sync and % operations (and related algorithms), so it is not recommended to continue using HashTable.
  • HashMap is recommended in non-competitive environments.
  • ConcurrentHashMap is recommended in multi-threaded environments.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.