The thread-unsafe nature of HashMap leads to an infinite loop

In our understanding, the problem that thread insecurity may bring is data inconsistency caused by multiple writes to an object, but we never expected that due to the thread insecurity feature of HashMap, there will be a situation of 100% CPU.

 

This happened recently in our production environment. The business volume at night is not large, and the CPU usage of a certain service of a machine soared to 340%, so we cut off the business of this machine. In the case of no business, this The CPU usage of the service still hasn't dropped.

I grabbed a dump and looked at the operation of the thread stack, and found that the three threads of this service are all doing the same thing, which is very strange:

 

"qtp1660201379-122235" prio=5 tid=122235 RUNNABLE
	at java.util.HashMap.getEntry(HashMap.java:465)
	   Local Variable: java.util.HashMap$Entry#77179
	   Local Variable: java.lang.String#6513
	at java.util.HashMap.get(HashMap.java:417)
......

 

It should be that these three threads are running an infinite loop, and then each thread occupies a CPU, which is exactly 300% of the CPU. After checking, due to the thread-unsafe nature of HashMap, there is a small probability that an infinite loop will be caused when multiple threads perform the same operation on the same HashMap.

 

Specifically, when many threads read the same HashMap, when a thread writes to this object without lock protection, it will cause an infinite loop with a small probability.

 

The JAVA team believes that HashMap is marked as thread-unsafe. In the case of multi-threading, this kind of problem is normal and not a bug.

Then it is recommended that you use ConcurrentHashmap to replace HashMap in a multi-threaded environment.

 

For the cause analysis of the specific infinite loop, see this article:

http://coolshell.cn/articles/9606.html

Guess you like

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