WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Guru · question 89 of 100

What is the difference between a HashMap and a LinkedHashMap in terms of thread-safety, and how can you optimize thread-safety for a LinkedHashMap?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

The HashMap and LinkedHashMap classes in Java Collections are both used to store key-value pairs, but they differ in the way they maintain the order of insertion and the thread-safety.

HashMap is not thread-safe, which means that if multiple threads access a HashMap concurrently and at least one of the threads modifies the map structurally, then it must be synchronized externally. This can be done by wrapping the HashMap with Collections.synchronizedMap() method, but this can lead to performance issues if many threads access the map at the same time.

LinkedHashMap, on the other hand, is a subclass of HashMap and maintains the insertion order of elements. It provides a predictable iteration order and supports limited structural modification operations like removal of the least recently accessed entry. LinkedHashMap is also not thread-safe, but can be made thread-safe by wrapping it with Collections.synchronizedMap() or by using a ConcurrentHashMap with equivalent functionality.

Here’s an example demonstrating the usage of LinkedHashMap:

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        Map<String, Integer> linkedHashMap = new LinkedHashMap<>();

        linkedHashMap.put("one", 1);
        linkedHashMap.put("two", 2);
        linkedHashMap.put("three", 3);

        for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Output:

one : 1
two : 2
three : 3

To optimize thread-safety for LinkedHashMap, one can use a ConcurrentHashMap with equivalent functionality. This can be achieved by using the ConcurrentHashMap constructor that takes an initialCapacity, loadFactor, and concurrencyLevel as parameters. The concurrencyLevel parameter determines the estimated number of concurrently updating threads, which can improve performance by reducing contention for locks.

Here’s an example demonstrating the usage of ConcurrentHashMap with equivalent functionality as LinkedHashMap:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        Map<String, Integer> concurrentHashMap = new ConcurrentHashMap<>(16, 0.75f, 4);

        concurrentHashMap.put("one", 1);
        concurrentHashMap.put("two", 2);
        concurrentHashMap.put("three", 3);

        for (Map.Entry<String, Integer> entry : concurrentHashMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Output:

one : 1
two : 2
three : 3

In summary, HashMap and LinkedHashMap are not thread-safe and can be made thread-safe by wrapping them with Collections.synchronizedMap(). LinkedHashMap maintains the insertion order of elements, while ConcurrentHashMap can be used as a thread-safe replacement for LinkedHashMap by specifying an appropriate concurrencyLevel.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics