SoFunction
Updated on 2025-04-24

Several ways JAVA ensures HashMap thread safety

In Java, HashMap is thread-insecure, which means that if multiple threads access and modify the same HashMap instance concurrently, it may lead to data inconsistency and other thread-safe issues. To ensure thread safety, the following methods can be considered:

1. Use

is an easy method provided by Java to make non-thread-safeHashMapPackaged as thread-safeMap. It is implemented by synchronizing the entire Map object at each method call.

Sample code:

import ;
import ;
import ;

public class SynchronizedMapExample {
    private final Map<String, String> map = (new HashMap<>());

    public void put(String key, String value) {
        (key, value);
    }

    public String get(String key) {
        return (key);
    }

    public static void main(String[] args) {
        SynchronizedMapExample example = new SynchronizedMapExample();
        ("key1", "value1");
        (("key1"));
    }
}

Notice:

Every visitmapWhen it is implicitlymapObject locking, which may lead to performance bottlenecks.

For traversal operations, manual synchronization is required:

synchronized(map) {
    for (&lt;String, String&gt; entry : ()) {
        // Iterative operation    }
}

2. Use ConcurrentHashMap

ConcurrentHashMapIt is Java concurrent package (A thread-safe Map implementation in ) . It adopts a segmented lock mechanism (improved to CAS operation in JDK 1.8) that provides better performance at higher concurrency levels.

Sample code:

import ;

public class ConcurrentHashMapExample {
    private final ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

    public void put(String key, String value) {
        (key, value);
    }

    public String get(String key) {
        return (key);
    }

    public static void main(String[] args) {
        ConcurrentHashMapExample example = new ConcurrentHashMapExample();
        ("key1", "value1");
        (("key1"));
    }
}

Features:

  • ConcurrentHashMapProvides higher concurrency performance because its operations implement segment lock or CAS operations internally.
  • Most common operations (such asputgetremove) can all be completed within O(1) time complexity.

3. Manually synchronize code blocks

By visitingHashMapWhen using synchronous code blocks to ensure thread safety. This approach allows for more fine-grained synchronization, but requires careful design to avoid deadlocks and performance issues.

Sample code:

import ;
import ;

public class ManualSynchronizedMap {
    private final Map<String, String> map = new HashMap<>();

    public void put(String key, String value) {
        synchronized(map) {
            (key, value);
        }
    }

    public String get(String key) {
        synchronized(map) {
            return (key);
        }
    }

    public static void main(String[] args) {
        ManualSynchronizedMap example = new ManualSynchronizedMap();
        ("key1", "value1");
        (("key1"));
    }
}

Notice:

  • Synchronous code blocks need to be managed manually, which may increase the risk of code complexity and errors.
  • Make sure to release the lock wherever possible and avoid deadlocks.

4. Use ReadWriteLock

ReadWriteLockProvides a mechanism to separate read locks and write locks, which allows multiple read threads to be accessed concurrently, while write threads need to have exclusive locks. This is especially useful in scenarios where more reads and less writes.

Sample code:

import ;
import ;
import ;
import ;

public class ReadWriteLockMap<K, V> {
    private final Map<K, V> map = new HashMap<>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    public V put(K key, V value) {
        ().lock();
        try {
            return (key, value);
        } finally {
            ().unlock();
        }
    }

    public V get(K key) {
        ().lock();
        try {
            return (key);
        } finally {
            ().unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockMap<String, String> example = new ReadWriteLockMap<>();
        ("key1", "value1");
        (("key1"));
    }
}

Features:

  • Read operations are concurrent, and write operations require exclusive locks, which are suitable for scenarios where more reads, less writes.
  • There are two types of locks (read lock and write lock), and the code is relatively complex.

Selection Guide

  • High concurrency performanceConcurrentHashMapIt is the best choice.
  • Simple implementationSuitable for simple thread safety needs.
  • Fine control: Manual synchronization code blocks are suitable for scenarios where customized synchronization logic is required.
  • Read more and write lessReadWriteLockVery effective in this scenario.

Choose the most appropriate method to ensure that according to the specific usage scenario and performance needsHashMapthread safety.

This is the end of this article about several ways JAVA ensures HashMap thread safety. For more related content on JAVA HashMap thread safety, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!