java split 内存,Java String.split内存泄漏?

I found that using String.substring is known for memory issues related to String.split.

Is there a memory leak in using String.split?

If yes what is the work-around for it?

Following link show correct usage of substring in Java.

One more blog which talk about possible MLK in substring.

解决方案

Update: Behavior has changed in 1.7.0_06: See this article: Changes to String internal representation made in Java 1.7.0_06 at java-performance.info.

As pointed out by @finnw there is indeed kind of a memory leak lurking around when using String.substring. The reason is that String.substring only returns a view of a portion of the given string, i.e., the underlying string is still kept in memory.

To force the creation of a new string, unrelated to the source, you'll have to use the new keyword. I.e., you'll have to do for instance

String[] parts = orig.split(";");

//String mySubstring = parts[i]; // keeps orig from being GC'd

String mySubstring = new String(parts[i]); // creates a new string.

or, perhaps more direct

String mySubstring = new String(orig.split(";")[i]);

I must say that this behavior seems "unnecessary" to me. It should be solvable using weak references or some other technique. (Especially considering that String is already a special class, part of the Java language specification.)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值