Writing java code creates a memory overflow condition

This will be an evil article. When you want to make a tragedy in someone's life, you may Google it. In the Java world, memory overflow is just a bug you may introduce in this case. Your victim will spend days or even weeks of sleepless nights in the office.

In this article, I will introduce two overflow methods, which are easy to understand and reproduce. And they are all case studies from real projects, but in order to let you grasp them clearly, I have simplified them.

However, rest assured that after we encounter and solve the overflow bug, similar cases will be more common than you think.

First, when using HashSet / HashMap, the key value is not used or its equals() / hashcode() method is incorrect, which will lead to a notorious error.

When you run the above code, you may expect it to run without problems. After all, the built-in cache scheme will only increase to 10000 elements, and then it will not increase any more. All keys have appeared in the HashMap. However, this is not the case. The element will continue to grow because the key class does not implement an appropriate equals () method after hashcode ().

The solution is simple. Just add an equals method as in the following example. But before you find the problem, you must have spent a lot of valuable brain cells.

The next thing you have to remind your friends is the operation related to string processing. It will behave strangely, especially when combined with JVM version differences. The internal working mechanism of string has been changed in JDK 7u6, so if you find that the product environment is only the difference of small version number, you are ready for the condition. Give the following code to your friend for debugging, and then ask him why this bug only appears in the product.

What's wrong with the above code? When it runs on the version before JDK 7u6, the returned string will save a reference to the string with the size of about 1m. If you set it to - xmx100m when running, you will get an unexpected oom error. Combined with the differences between the platforms and versions in your experimental environment, the event of brain injury occurs.

Now if you want to cover up your footprint, we can introduce some more advanced concepts. such as

I hope we gave you some raw materials for thinking and some materials when you want to repair someone. This will lead to endless debugging. Unless your friend uses plumbr to find the overflow location.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>