Junior
Is HashMap collection thread-safe?
sobes.tech AI
Answer from AI
No. HashMap is not thread-safe. Concurrent access from multiple threads can lead to issues such as data loss or infinite loops (in older Java versions).
To ensure thread safety in similar scenarios, you can use Hashtable (deprecated) or ConcurrentHashMap (recommended in modern applications). ConcurrentHashMap provides better performance through more granular locking.
Example of using ConcurrentHashMap:
// Using ConcurrentHashMap for thread-safe map
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
public class ThreadSafeMapExample {
public static void main(String[] args) {
Map<String, Integer> threadSafeMap = new ConcurrentHashMap<>();
// Safely adding elements from different threads
Runnable task = () -> {
for (int i = 0; i < 100; i++) {
threadSafeMap.put("key" + i, i);
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Map size: " + threadSafeMap.size());
}
}