109k views
5 votes
Which is thread-safe, HashMap or Hashtable?
1) HashMap
2) Hashtable

1 Answer

4 votes

Final answer:

HashMap is thread-unsafe, while Hashtable is thread-safe.

Step-by-step explanation:

HashMap is a thread-unsafe class in Java, while Hashtable is thread-safe. This means that multiple threads can access the Hashtable concurrently without any issues. However, if multiple threads try to modify a HashMap at the same time, it can lead to data corruption and unexpected behavior.

For example, if two threads try to modify a HashMap by adding elements to it simultaneously, they may overwrite each other's changes and the final state of the HashMap can be incorrect. On the other hand, Hashtable uses synchronized methods to ensure that only one thread can access or modify it at a time, preventing any concurrency issues.

User RodXander
by
7.4k points