the difference between HashMap and Concurrenthashmap.
1. HashMap is non-thread-safe and Conurrenthashmap is thread-safe.
2. Concurrenthashmap the entire hash bucket is segmented segment, that is, the large array is divided into a few small fragments segment, and each small fragment segment above the existence of a lock, Then, when inserting the element, we need to find out which fragment segment to insert, and then insert it on this fragment, and we need to get the segment lock.
3.ConcurrentHashMap makes lock granularity more granular, and concurrency performance is better.
concurrenthashmap thread safety. Concurrenthashmap How to ensure thread safety.
1. The Hashtable container is inefficient in a highly competitive concurrency environment because all threads that access Hashtable must compete for the same lock, if there are multiple locks in the container, and each lock is used for a portion of the data in the lock container, when multithreading accesses data from different data segments in the container, There is no lock competition between the threads, which can effectively improve the efficiency of concurrent access, which is the segmented lock technology used by Concurrenthashmap, first divides the data into a section of storage, and then gives each piece of data a lock, when a thread takes a lock to access one of the data, Data from other segments can also be accessed by other threads.
2. The get operation is efficient in that the entire get process does not need to be locked, unless the read value is empty to lock and reread. The shared variables that will be used in the Get method are defined as volatile if used to count the current segment size and the value of the hashentry used to store the values. Variables defined as volatile, able to maintain visibility between threads, can be read at the same time, and guaranteed not to read expired values, but can only be single-threaded write (there is a case can be multi-threaded writing, that is, the value written is not dependent on the original value), In the get operation, it is necessary to read only the count and value that do not need to write the shared variable, so it can be unlocked.
3. The Put method first navigates to the segment and then inserts in the segment. The insert operation takes two steps, the first step is to determine if you need to expand the hashentry array in segment, and the second position to add the element's location and place it in the hashentry array.