java string 内存泄漏_String类substring方法导致的Java内存泄漏问题 (转)

此问题在项目中被发现,经查看JDK源码(JDK1.6),String类的public String substring(int beginIndex, int endIndex)的实现让我很意外。

想重现这个场景很容易,请看代码。

package TestStringOutOfMemory;

import java.util.ArrayList;

import java.util.List;

public class LeakTest {

public static void main(String...args) {

List handler = new ArrayList();

for(int i = 0; i < 100000; i++) {

Huge h = new Huge();

handler.add(h.getSubString(1, 5));

}

}

}

class Huge {

private String str = new String(new char[100000]);

public String getSubString(int begin, int end) {

return new String(str.substring(begin, end));

}

}

执行此代码结果:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

问题就出在Huge类的 getSubString 方法,它调用了String类的substring方法。

来让我们看看 substring 类的实现吧,JDK源码如下:

public String substring(int beginIndex, int endIndex) {

if (beginIndex < 0) {

throw new StringIndexOutOfBoundsException(beginIndex);

}

if (endIndex > count) {

throw new StringIndexOutOfBoundsException(endIndex);

}

if (beginIndex > endIndex) {

throw new StringIndexOutOfBoundsException(endIndex - beginIndex);

}

return ((beginIndex == 0) && (endIndex == count)) ? this :

new String(offset + beginIndex, endIndex - beginIndex, value);

}

再让我们接下来看看 new String(offset + beginIndex, endIndex - beginIndex, value); 的实现:

// Package private constructor which shares value array for speed.

String(int offset, int count, char value[]) {

this.value = value;

this.offset = offset;

this.count = count;

}

char[] value 数组被共享了。

在我们的main函数里的循环中,每循环一次后,我们希望Huge对象被回收,且释放它占有的内存。

但实际上 private String str = new String(new char[100000]); 占有的内存并不会被释放。

因为 我们通过 Huge 类的 getSubString 方法得到的 String 对象还存在(存在于handler的列表中),

它虽然是 length 只有 4 的对象,却享有着 char[100000] 的空间。

解决方案:

可以修改Huge 类的 getSubString 方法如下:

public String getSubString(int begin, int end) {

return new String(str.substring(begin, end));

}

只要再套一个String的构造方法即可。

至于为什么,看看JDK源码,一看便知了。这里就不贴出来了。

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-01-06 10:10

浏览 1133

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值