Is Hashmap thread safe? Why?

Is Hashmap thread safe? Why?

Not thread safe. If multiple threads simultaneously access a hash map and at least one of them structurally modifies the map, it must maintain external synchronization. This is typically done by synchronizing the object that naturally encapsulates the map. If no such object exists, the Collections.synchronizedMap method should be used to "wrap" the map. This is best done at creation time to prevent accidental asynchronous access to the map. The above method will be called when the hashmap performs the put operation. Now if thread A and thread B call addEntry on the same array position at the same time, both threads will get the current head node at the same time, and then after A writes the new head node, B also writes the new head node, then B's write operation will overwrite A's write operation, causing A's write operation to be lost.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325233624&siteId=291194637