Java字符串的substring真的會引起內存泄露麼?

在Java中開發,String是我們開發程序可以說必須要使用的類型,String有一個substring方法用來截取字符串,我們想必也常常使用。但是你知道麼,關於Java 6中的substring是否會引起內存泄露,在國外的論壇和社區有着一些討論,以至於Java官方已經將其標記成bug,並且爲此Java 7 還重新進行了實現。讀到這裏可能你的問題就來了,substring怎麼會引起內存泄露呢?那麼我們就帶着問題,走進小黑屋,看看substring有沒有內存泄露,又是怎麼導致所謂的內存泄露。

基本介紹

substring方法提供兩種重載,第一種爲只接受開始截取位置一個參數的方法。

public String substring(int beginIndex)

比如我們使用上面的方法,”unhappy”.substring(2) 返回結果 ”happy”

另一種重載就是接受一個開始截取位置和一個結束截取位置的參數的方法。

public String substring(int beginIndex, int endIndex)

使用這個方法,”smiles”.substring(1, 5) 返回結果 ”mile”

通過這個介紹我們基本瞭解了substring的作用,這樣便於我們理解下面的內容。

準備工作

因爲這個問題出現的情況在Java 6,如果你的Java版本號不是Java 6 需要調整一下。

終端調整(適用於Mac系統)

查看java版本號

13:03 $ java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

切換到1.6

export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)

Ubuntu使用alternatives –config java,Fedora上面使用alternatives –config java。

如果你使用Eclipse,可以選擇工程,右擊,選擇Properties(屬性)— Java Compiler(Java編譯器)進行特殊指定。

問題重現

這裏貼一下java官方bug裏用到的重現問題的代碼。

public class TestGC {
    private String largeString = new String(new byte[100000]);

    String getString() {
        return this.largeString.substring(0,2);
    }

    public static void main(String[] args) {
        java.util.ArrayList list = new java.util.ArrayList();
        for (int i = 0; i < 1000000; i++) {
            TestGC gc = new TestGC();
            list.add(gc.getString());
        }
    }
}

然而上面的代碼,只要使用Java 6 (Java 7和8 都不會拋出異常)運行一下就會報java.lang.OutOfMemoryError: Java heap space的異常,這說明沒有足夠的堆內存供我們創建對象,JVM選擇了拋出異常操作。

於是有人會說,是因爲你每個循環中創建了一個TestGC對象,雖然我們加入ArrayList只是兩個字符的字符串,但是這個對象中又存儲largeString這麼大的對象,這樣必然會造成OOM的。

然而,其實你說的不對。比如我們看一下這樣的代碼,我們只修改getString方法。

public class TestGC {
    private String largeString = new String(new byte[100000]);

    String getString() {
        //return this.largeString.substring(0,2);
      return new String("ab");
    }

    public static void main(String[] args) {
        java.util.ArrayList list = new java.util.ArrayList();
        for (int i = 0; i < 1000000; i++) {
            TestGC gc = new TestGC();
            list.add(gc.getString());
        }

    }
}

執行上面的方法,並不會導致OOM異常,因爲我們持有的時1000000個ab字符串對象,而TestGC對象(包括其中的largeString)會在java的垃圾回收中釋放掉。所以這裏不會存在內存溢出。

那麼究竟是什麼導致的內存泄露呢?要研究這個問題,我們需要看一下方法的實現,即可。

深入Java 6實現

在String類中存在這樣三個屬性

  • value 字符數組,存儲字符串實際的內容
  • offset 該字符串在字符數組value中的起始位置
  • count 字符串包含的字符的長度

Java 6中substring的實現

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);
}

上述方法調用的構造方法

//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;
}

當我們讀完上述的代碼,我們應該會豁然開朗,原來是這個樣子啊!

當我們調用字符串a的substring得到字符串b,其實這個操作,無非就是調整了一下b的offset和count,用到的內容還是a之前的value字符數組,並沒有重新創建新的專屬於b的內容字符數組。

舉個和上面重現代碼相關的例子,比如我們有一個1G的字符串a,我們使用substring(0,2)得到了一個只有兩個字符的字符串b,如果b的生命週期要長於a或者手動設置a爲null,當垃圾回收進行後,a被回收掉,b沒有回收掉,那麼這1G的內存佔用依舊存在,因爲b持有這1G大小的字符數組的引用。

看到這裏,大家應該可以明白上面的代碼爲什麼出現內存溢出了。

共享內容字符數組

其實substring中生成的字符串與原字符串共享內容數組是一個很棒的設計,這樣避免了每次進行substring重新進行字符數組複製。正如其文檔說明的,共享內容字符數組爲了就是速度。但是對於本例中的問題,共享內容字符數組顯得有點蹩腳。

如何解決

對於之前比較不常見的1G字符串只截取2個字符的情況可以使用下面的代碼,這樣的話,就不會持有1G字符串的內容數組引用了。

String littleString = new String(largeString.substring(0,2));

下面的這個構造方法,在源字符串內容數組長度大於字符串長度時,進行數組複製,新的字符串會創建一個只包含源字符串內容的字符數組。

public String(String original) {
  int size = original.count;
  char[] originalValue = original.value;
  char[] v;
  if (originalValue.length > size) {
      // The array representing the String is bigger than the new
      // String itself.  Perhaps this constructor is being called
      // in order to trim the baggage, so make a copy of the array.
      int off = original.offset;
      v = Arrays.copyOfRange(originalValue, off, off+size);
  } else {
      // The array representing the String is the same
      // size as the String, so no point in making a copy.
      v = originalValue;
  }
  this.offset = 0;
  this.count = size;
  this.value = v;
}

Java 7 實現

在Java 7 中substring的實現拋棄了之前的內容字符數組共享的機制,對於子字符串(自身除外)採用了數組複製實現單個字符串持有自己的應該擁有的內容。

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
      throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > value.length) {
      throw new StringIndexOutOfBoundsException(endIndex);
    }
    int subLen = endIndex - beginIndex;
    if (subLen < 0) {
      throw new StringIndexOutOfBoundsException(subLen);
    }
    return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
}

substring方法中調用的構造方法,進行內容字符數組複製。

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);
}

真的是內存泄露麼

我們知道了substring某些情況下可能引起內存問題,但是這個叫做內存泄露麼?

其實個人認爲這個不應該算爲內存泄露,使用substring生成的字符串b固然會持有原有字符串a的內容數組引用,但是當a和b都被回收之後,該字符數組的內容也是可以被垃圾回收掉的。

哪個版本實現的好

關於Java 7 對substring做的修改,收到了褒貶不一的反饋。

個人更加傾向於Java 6的實現,當進行substring時,使用共享內容字符數組,速度會更快,不用重新申請內存。雖然有可能出現本文中的內存性能問題,但也是有方法可以解決的。

Java 7的實現不需要程序員特殊操作避免了本文中問題,但是進行每次substring的操作性能總會比java 6 的實現要差一些。這種實現顯得有點“糟糕”。

問題的價值

雖然這個問題出現在Java 6並且Java 7中已經修復,但並不代表我們就不需要了解,況且Java 7的重新實現被噴的很厲害。

其實這個問題的價值,還是比較寶貴的,尤其是內容字符數組共享這個優化的實現。希望可以爲大家以後的設計實現提供幫助和一些想法。

受影響的方法

trim和subSequence都存在調用substring的操作。Java 6和Java 7 substring實現的更改也間接影響到了這些方法。

參考資源

以下三篇文章寫得都比較不錯,但是都稍微有一些問題,我都已經標明出來,大家閱讀時,需要注意。

注意

上面的重現問題的代碼中

String getString() {
  //return this.largeString.substring(0,2);
      return new String("ab");
}

這裏最好不要寫成下面這樣,因爲在JVM中存在字符串常量池,”ab”不會重新創建新字符串,所有的變量都會引用一個對象,而使用new String()則每次重新創建對象。

String getString() {
      return "ab";
}

關於字符串常量池,以後的文章會有介紹。

另外,這篇文章對Java字符串的10大問題進行了詳細的介紹,有興趣的朋友也可以看看。

原文地址:http://www.codeceo.com/article/java-substring-memory.html

發佈了29 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章