ITeye博客

String substring的内存泄漏分析和优化方法

MouseLearnJava · 2013-08-21 23:26 · Java · 编程语言 · Java · String · substring · Markdown

本文将对String.substring方法可能产生内存泄漏的问题进行分析,并给出相应的优化方法。 [u][b]String.substring内存泄漏分析[/b][/u] 首先看一下JDK6 String.substring的源代码: [code="java"]public final class String implements java.io.Serializable, Comparable, CharSequence { /** The value is used for character storage. */ private final char value[]; /** * Returns a new string that is a substring of this string. The * substring begins with the character at the specified index and * extends to the end of this string.

* Examples: *

     * "unhappy".substring(2) returns "happy"
 * "Harbison".substring(3) returns "bison"
 * "emptiness".substring(9) returns "" (an empty string)
 * 

* * @param beginIndex the beginning index, inclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if * beginIndex is negative or larger than the * length of this String object. */ public String substring(int beginIndex) { return substring(beginIndex, count); } /** * Returns a new string that is a substring of this string. The * substring begins at the specified beginIndex and * extends to the character at index endIndex - 1. * Thus the length of the substring is endIndex-beginIndex. *

* Examples: *

     * "hamburger".substring(4, 8) returns "urge"
 * "smiles".substring(1, 5) returns "mile"
 * 

* * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * beginIndex is negative, or * endIndex is larger than the length of * this String object, or * beginIndex is larger than * endIndex. */ 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); } }[/code] 从上述的源代码可以看出,使用substring获取子字符串方法中,原有字符串的内容value(char[])将继续重用。这种方式提高了运算速度却要在内存中保留原来字符串的内容。 例如: 读取一个5000个字符的字符串,采用substring截取其中的30个字符,在这种情况下,30个字符在内存中还是使用了5000个字符。 设想一下:如果字符串更大,比如一百万个字符,而substring只需要其中的几十个,这样的情况下将会占有较多的内存空间。如果实例多需要调用的次数多,那么很容易造成内存泄漏。 请看下面的一个例子: [code="java"]package my.memoryLeak; import java.util.ArrayList; import java.util.List; public class MemoryLeakExample { public static void main(String[] args) { /** -XX:PermSize=1M -XX:MaxPermSize=1M */ List substringList = new ArrayList(); /** * 循环3000次。 * 第i次循环截取前i个字符串 */ for (int i = 1; i <= 3000; i++) { HugeString huge = new HugeString(); System.out.println(i); substringList.add(huge.subString1(0, i)); } } } class HugeString { private String str = new String(new char[1000000]); /** * 调用String的subString方法来实现。 * 例如: 读取一个5000个字符的字符串,采用substring截取其中的30个字符,在这种情况下,30个字符在内存中还是使用了5000个字符。 * 设想一下:如果字符串更大,比如一百万个字符,而substring只需要其中的几十个, * 这样的情况下会将会占有较多的内存空间。如果实例多需要调用的次数多,那么很容易造成内存泄漏。 * Exception in thread "main" java.lang.OutOfMemoryError: Java heap space * at java.util.Arrays.copyOf(Unknown Source) * at java.lang.String.(Unknown Source) * at my.memoryLeak.Huge.(LeakTest.java:38) * at my.memoryLeak.MemoryLeakExample.main(MemoryLeakExample.java:13) * */ public String subString1(int begin, int end) { return str.substring(begin, end); } /** * 采用新建的方式,避免在内存中占有较多的内容。 */ public String subString2(int begin, int end) { return new String(str.substring(begin, end)); } /** * 将substring的内容存放到常量池。 * 这种情况下,会用到PermGen space,如果过度使用,可能导致PermGen Sapce用完,跑出异常。 * * 可以使用如下参数调整大小,如 * -XX:PermSize=1M -XX:MaxPermSize=1M * * Exception in thread "main" java.lang.OutOfMemoryError: PermGen space * at java.lang.String.intern(Native Method) * at my.memoryLeak.HugeString.subString3(MemoryLeakExample.java:55) * at my.memoryLeak.MemoryLeakExample.main(MemoryLeakExample.java:15) */ public String subString3(int begin, int end) { return str.substring(begin, end).intern(); } }[/code] [u][b]避免substring的优化方法[/b][/u] [color=blue][b]1. 创建新的字符串。[/b][/color][code="java"] /** * 采用新建的方式,避免在内存中占有较多的内容。 */ public String subString2(int begin, int end) { return new String(str.substring(begin, end)); }[/code] [color=blue][b]2. 使用intern()[/b][/color] [code="java"] /** * 将substring的内容存放到常量池。 * 这种情况下,会用到PermGen space,如果过度使用,可能导致PermGen Sapce用完,跑出异常。 * * 可以使用如下参数调整大小,如 * -XX:PermSize=1M -XX:MaxPermSize=1M * * Exception in thread "main" java.lang.OutOfMemoryError: PermGen space * at java.lang.String.intern(Native Method) * at my.memoryLeak.HugeString.subString3(MemoryLeakExample.java:55) * at my.memoryLeak.MemoryLeakExample.main(MemoryLeakExample.java:15) */ public String subString3(int begin, int end) { return str.substring(begin, end).intern(); }[/code] 在测试代码中,采用默认VM参数的,分别调用huge.subString1(0, i), huge.subString2(0, i)和huge.subString3(0, i)运行程序,得到的结果如下: a)采用huge.subString1(0, i)遇到OutOfMemoryError [img]http://dl2.iteye.com/upload/attachment/0088/4901/dcc5b8a1-264b-3f66-92c4-40c6b5b222b9.jpg[/img] b)采用huge.subString2(0, i)和huge.subString3(0, i)的运行正常。 采用intern()方法会有其它的影响,因为我们将使用PermGen Space. 除非VM有足够的空间,否则也会抛出OutOfMemoryError. 比如: 使用参数-XX:PermSize=1M -XX:MaxPermSize=1M 采用huge.subString3(0, i)再运行一下: [img]http://dl2.iteye.com/upload/attachment/0088/4899/feaba6e3-0730-3970-83b8-a05ef1dd14da.jpg[/img] 在这种情况下,只有采用huge.subString2(0, i)的方式还能正常运行,采用huge.subString1(0, i)和huge.subString3(0, i)方法都产生了OutOfMemoryError。 比较一下打印出来的循环次数,采用intern()方法运行次数比直接采用String.substring的运行次数多很多。 [b]通过上面的例子可以得出如下几个结论:[/b] 1. String.substring存在内存泄漏的危险。 2. 采用新建字符串和String.intern()的方法可以优化直接调用String.substring。 首先选择的是新建字符串。其次才是选择通过intern()方法。intern()方法使用有其局限性。这个只有在从大字符串中截取比较小的子字符串,并且原来的字符串不需要再继续使用的场景下有较好的作用。

评论(4)

  1. #4 楼 · MouseLearnJava · 2013-08-23 22:57

    frank-liu writes:

    楼主所说的这种场景适用于连续访问大的字符串的情况,比如说从网上连续读字符串,每次读出来一大堆的时候取中间一部分。在jdk6及更早的版本里用substring()方法会导致新生成的string实际上内部还是有指向原来数组内部char[]的引用,gc就不能把生成的这些大的字符串回收,这样就导致内存溢出了。
    只是举的这个例子有点容易让人误解,因为ArrayList里面添加的元素如果不用remove方法移除的话,后面只要这个ArrayList还在被使用它里面的元素就gc不了。这样如果加入的元素过多,有可能导致把系统内存耗光,这就相当于故意耗内存而不是substring的错了。
    

    谢谢你的评论。

    确实,如果一直创建对象并放入ArrayList中也会引起堆内存的溢出。

  2. #3 楼 · frank-liu · 2013-08-23 16:11

    楼主所说的这种场景适用于连续访问大的字符串的情况,比如说从网上连续读字符串,每次读出来一大堆的时候取中间一部分。在jdk6及更早的版本里用substring()方法会导致新生成的string实际上内部还是有指向原来数组内部char的引用,gc就不能把生成的这些大的字符串回收,这样就导致内存溢出了。 只是举的这个例子有点容易让人误解,因为ArrayList里面添加的元素如果不用remove方法移除的话,后面只要这个ArrayList还在被使用它里面的元素就gc不了。这样如果加入的元素过多,有可能导致把系统内存耗光,这就相当于故意耗内存而不是substring的错了。

  3. #2 楼 · MouseLearnJava · 2013-08-22 10:19

    JDK1.7后对substring做了改进。JDK1.6及其以下的版本中substring都会共享value。我贴的代码是JDK1.6版本的。

    上面的例子只是说明了substring可能产生的问题,以下面的代码为例,

            /** -XX:PermSize=1M -XX:MaxPermSize=1M */  
           List<String> substringList = new ArrayList<String>();   
              
           /**  
            * 循环3000次。  
            * 第i次循环截取前i个字符串  
             */  
           for (int i = 1; i <= 3000; i++) {   
              HugeString huge = new HugeString();   
              System.out.println(i);   
              substringList.add(huge.subString1(0, i));   
           } 
    

    尽管我们使用了huge.substring截取了很小部分的子字符串,却占用了char的内存空间。这循环体执行过程中,huge添加到了list中,垃圾回收机制并不回回收huge中的字符串。

    随着实例的增多,占用的内存空间也将增多,这就是导致出现问题的原因。

    目前,很多系统依然采用1.6及其以下的JDK版本,所以,使用substring时还是需要小心点的。 不过,一般情况下,这种问题很少发生。

  4. #1 楼 · lbfhappy · 2013-08-22 09:05

    我这里jdk1.7的源码里面是看不到任何内存泄漏的可能的啊。

    
        public String(char value[], int offset, int count) {
            if (offset < 0) {
                throw new StringIndexOutOfBoundsException(offset);
            }
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            // Note: offset or count might be near -1>>>1.
            if (offset > value.length - count) {
                throw new StringIndexOutOfBoundsException(offset + count);
            }
            this.value = Arrays.copyOfRange(value, offset, offset+count);
        }
    
    
    

    以上是String的构造方法,这里的value并没有公用,而是调用Arrays.copyOfRange的方法拷贝出了需要用的char的数组,而不是直接使用原来的。 并且就算是直接使用原来的,共用同一个引用的话,那更是一点问题都没有啊,就算是再多的引用指向,也不会增加多少内存啊,只是多一个引用而已,又不会多很多个char的内存分配。

    不知道楼主是在什么版本的JDK下面测试出来的结果的。

评论功能维护中,当前仅展示历史评论。