Java String.split内存泄漏? [英] Java String.split memory leak?

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

问题描述

我发现使用 String.substring 已知与 String.split 相关的内存问题。

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

使用 String.split 是否存在内存泄漏?

Is there a memory leak in using String.split?

如果是,它的解决方法是什么?

If yes what is the work-around for it?

以下链接显示了Java中子字符串的正确用法。

Following link show correct usage of substring in Java.

http://错误。 sun.com/bugdatabase/view_bug.do?bug_id=4513622

还有一篇关于可能性的博客子串中的MLK。

One more blog which talk about possible MLK in substring.

http://nflath.com/2009/07/the-dangers-of-stringsubstring/

推荐答案

更新:行为在1.7.0_06中发生了变化:请参阅此文章:变化to java 1.7.0_06中的字符串内部表示在java-performance.info。

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.

如指出的那样通过 @finnw ,使用 String.substring时确实存在潜在的内存泄漏。原因是 String.substring 只返回给定字符串的一部分视图,即基础字符串仍保留在内存中

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.

要强制创建与源无关的新字符串,您必须使用 new 关键词。即,你必须做的事情

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.

或者更直接

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






我必须说这种行为似乎不必要对我来说。它应该可以使用弱引用或其他技术来解决。 (特别是考虑到 String 已经是一个特殊的类,它是Java语言规范的一部分。)


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.)

这篇关于Java String.split内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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