JavaRush /Java Blog /Random EN /HashMap and ConcurrentHashMap are popular interview quest...
furs08
Level 11

HashMap and ConcurrentHashMap are popular interview questions

Published in the Random EN group
In my last preview, I talked about “How HashMap Works in Java ”. I talked about the internals of this class and how they fit into the concept. But when I was asked about HashMap and related things, the interviewer didn't just stop at the basic concept. In the course of the discussion, different directions are touched, in the end it all comes down to whether you really understand these things or not. HashMap and ConcurrentHashMap popular interview questions - 1In this preview, I will try to cover all the main topics of interview questions: Topics covered:
  1. How to create a key for HashMap?
  2. Differences between HashMap and ConcurrentHashMap?
  3. Differences between Collections.synchronizedMap(HashMap) and HashMap?
  4. Differences between ConcurrentHashMap and Collections.synchronizedMap(HashMap)?
  5. Differences between HashMap and HashTable?
  6. Differences between HashTable and Collections.synchronizedMap(HashMap)?
  7. Impact of random/fixed hashCode() values ​​on a key
  8. Using HashMap in unsynchronized multi-threaded application code
So let's get started:
  1. Creating a key for HashMap

    One of the main needs is that we must return the value of the object without error. Right? Otherwise, it is not clear how to imagine the data structure that you are designing. It will be impossible to use. To decide that we have created a good key, we need to know how HashMap works. The work of HashMap is built on the principles of Hashing. The key in the hash code is primarily used in conjunction with the equals() method to add and look up an element in a HashMap. If the hash code of an object changes to another pair of key - value (key-value), then the value from the map (Map) is almost impossible to get. This case is called a memory leak. To avoid this, the key and map must be unchanged. This is the main reason why immutable classes such as String,

    But you need to remember that immutability is recommended, but not required. If you want to make the key a mutable object, then you must make sure that the key object does not change the object's hash code. This can be done by overriding the hashCode() method. In addition, key classes must work correctly with the hashCode() and equals() methods to avoid unwanted and surprising runtime behavior.

  2. Differences between HashMap and ConcurrentHashMap

    To better visualize СoncurrentHashMap, you need to consider this class as a group of HashMaps. To take and put values ​​of pairs (key-value) in a HashMap, you need to calculate the hash code and find the correct segment of the Collection.Entry array. In ConcurrentHashMap, the difference lies in the internal structure for storing key-value pairs. ConcurrentHashMap has an additional concept of segments. It will be easy to understand if you imagine that one segment is equivalent to one HashMap [conceptually]. The ConcurrentHashMap is split into many segments (default is 16) upon initialization. ConcurrentHashMap like threads about (16) access this segment concurrently, each thread running concurrently with high concurrency. Hence, if your key-value pair is stored in segment 10, you don't need to lock the other 15 segments additionally.

    HashMap and ConcurrentHashMap popular interview questions - 2

    In other words, the Concurrent HashMap uses many locks, and each lock manages one segment of the structure. Data installations in a particular shard are blocked from being received in that shard so update operations are synchronized. When receiving data, reading on the fly is used without synchronization. If you read data on the fly, then the segment is blocked and the write is made to the synchronized block.

  3. Differences between HashMap and Collection.synchronizedMap(HashMap)

    Everything is really simple! HashMap is not synchronized and Collection.synchronizedMap(HashMap) returns wrapped HashMap methods that are synchronized get and put methods.

    In fact, Collection.synchronizedMap(HashMap) of the internally created SunchronizedMap inner class contains the key-value pairs passed to the HashMap as an argument. Such an example of inner classes does not change anything in the initial parameters of the HashMap and is completely independent.

  4. Differences between ConcurrentHashMap and Collections.synchronizedMap(HashMap)

    Both are synchronized versions of HashMap with differences in functionality and internal structure. As stated above, ConcurrentHashMap consists of inner segments, which can be considered as independent HashMap's conceptually. All these segments can be blocked by separate threads executing at the same time. This way multiple threads can simultaneously get/put key-value pairs from ConcurrentHashMap without blocking/waiting for each other.

    From Collections.synchronizedMap() we get a synchronized version of the HashMap and access in a blocking manner. This means that if multiple threads try to access a synchronizedMap at the same time, they will be allowed to take/put key-value pairs over the same synchronized image.

  5. Differences between HashMap and HashTable

    This question is also simple. The main difference is that HashTable is synchronized while HashMap is not. If asked for other reasons, tell them that HashTable is a legacy class (part of JDK 1.0) that was derived from a collection by implementing the Map interface later. It still has things that are not in HashMap such as Enumerators (counters). Another minor reason is that HashMap supports a null key (rendered as empty memory). HashTable does not support a null key and throws a NullPointerException when attempting to set one.

  6. Differences between HashTable and Collection.synchronized(HashMap)

    Until now, you may have only known about their similarities. Both are synchronized versions of collections. Both have synchronized methods internally. Both block threads and make you wait when you can take / put something in the collection. So what are the differences? Fine! There are no major differences for the above reasons. The performance of both is the same. The only thing that distinguishes them is that HashTable is an inherited class, it has received its own additional functions such as Enumerators (counters).

  7. The effect of random/fixed values ​​on a key value.

    Influence in both cases whether fixed value or random will have the same result and this is inexplicable behavior. Of great importance is the place in the HashMap where to put the key-value pair and where to restore. If the position of the key object changes every time, then its position will be calculated in a different way each time. Thus, the object stored in the HashMap will be lost forever with minimal possibility of recovery. Therefore, key values ​​are immutable and return unique values ​​each time.

  8. Using HashMap in unsynchronized code of multi-threaded applications.

    - in the worst case, this can cause an infinite loop.

    - Yes.

    “You were right, it could indeed lead to an endless loop. You ask: "How?"

    - Fine! Here's the reason!

    HashMap has the concept of re-hashing when it reaches its upper limit. This is the process of creating a new area of ​​memory and copying existing elements there. Let's say Thread A put a key-value pair into a Map and rehashing started, at the same time Thread B started manipulating a memory area using a put operation. During rehashing, it is possible to create a circular dependency where an element residing in a reference leaf [in any memory location] can point to any previous node in the same memory location. This will lead to an infinite loop since the rehash code contains while(TRUE) {//get next node} which will run indefinitely.

    Take a close look at this code containing a transfer method using the rehash operation:

    public Object get(Object key) {
        Object k = maskNull(key);
        int hash = hash(k);
        int i = indexFor(hash, table.length);
        Entry e = table[i];
    
        //While true is always a bad practice and cause infinite loops
    
        while (true) {
            if (e == null)
                return e;
            if (e.hash == hash && eq(k, e.key))
                return e.value;
            e = e.next;
        }
    }

    More on this in the next article. If you found the article useful please share with your friends! Happy learning!

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION