String类中的substring方法导致内存泄漏 [英] substring method in String class causes memory leak

查看:333
本文介绍了String类中的substring方法导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说String类中的 substring 方法会导致内存泄漏。这是真的吗?怎么样?有什么替代方案吗?

特别是寻找答案,
在java中可能导致内存泄漏的所有其他事情是什么?这将有助于我在编码时注意。

It is said that substring method in String class causes memory leak. Is it true? How? What is an alternative for it?
Especially looking for answer,
What are all other things which can causes of memory leak in java? This will help me to take care while coding.

推荐答案

在以前版本的JDK中,<$ c $的实现c> substring 方法将构建一个新的 String 对象,保持对整个char数组的引用,以避免复制它。因此,您可能无意中仅使用一个字符串保留对非常大的字符数组的引用。 这是一个可能导致错误的示例

In past versions of the JDK, the implementation of the substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. You could thus inadvertently keep a reference to a very big character array with just a one character string. Here's an example of a bug this could induce.

此方法现已更改,此泄漏不再存在。

This method has now been changed and this "leak" doesn't exist anymore.

如果您想使用旧的JDK(即早于OpenJDK 7,Update 6)并且你希望在 substring 之后有最小的字符串,使用构造函数取另一个字符串:

If you want to use an old JDK (that is older than OpenJDK 7, Update 6) and you want to have minimal strings after substring, use the constructor taking another string :

String s2 = new String(s1.substring(0,1));

至于你的第二个问题,关于其他可能导致java内存泄漏的事情,它是不可能以建设性的方式回答。在java标准库中没有很多实例可以很容易地保持对对象的隐藏引用。在一般情况下,请注意您构建的所有引用,可能是未清除的集合或外部资源(文件,数据库事务,本机窗口小部件等)中可能出现的最常见问题。

As for your second question, regarding " other things which can causes of memory leak in java", it's impossible to answer in a constructive way. There aren't in java standard libs many instances of cases where you could so easily keep hidden references to objects. In the general case, pay attention to all the references you build, the most frequent problems probably arising in uncleaned collections or external resources (files, database transactions, native widgets, etc.).

这篇关于String类中的substring方法导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆