原文地址html
http://droidyue.com/blog/2014/12/14/substring-memory-issue-in-java/ java
在Java中開發,String是咱們開發程序能夠說必需要使用的類型,String有一個substring方法用來截取字符串,咱們想必也經常使用。可是你知道麼,關於Java 6中的substring是否會引發內存泄露,在國外的論壇和社區有着一些討論,以致於Java官方已經將其標記成bug,而且爲此Java 7 還從新進行了實現。讀到這裏可能你的問題就來了,substring怎麼會引發內存泄露呢?那麼咱們就帶着問題,走進小黑屋,看看substring有沒有內存泄露,又是怎麼致使所謂的內存泄露。程序員
基本介紹數組
substring方法提供兩種重載,第一種爲只接受開始截取位置一個參數的方法。app
public String substring(int beginIndex)
好比咱們使用上面的方法,"unhappy".substring(2) 返回結果 "happy"ide
另外一種重載就是接受一個開始截取位置和一個結束截取位置的參數的方法。性能
public String substring(int beginIndex, int endIndex)
使用這個方法,"smiles".substring(1, 5) 返回結果 "mile"測試
經過這個介紹咱們基本瞭解了substring的做用,這樣便於咱們理解下面的內容。優化
準備工做ui
由於這個問題出現的狀況在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實現的更改也間接影響到了這些方法。
參考資源
如下三篇文章寫得都比較不錯,可是都稍微有一些問題,我都已經標明出來,你們閱讀時,須要注意。
The substring() Method in JDK 6 and JDK 7 本文中解決java6中問題提到的字符串拼接不推薦,具體緣由能夠參考Java細節:字符串的拼接
How SubString method works in Java – Memory Leak Fixed in JDK 1.7 本文中提到的有一個概念錯誤,新的字符串不會阻止舊的字符串被回收,而是阻止舊字符串中的內容字符數組。閱讀時須要注意。
JDK-4513622 : (str) keeping a substring of a field prevents GC for object 本文中提到的有一個測試,使用非new的形式有一點問題,其忽視了字符串常量池的存在,具體查看下面的注意。
注意
上面的重現問題的代碼中
String getString() { //return this.largeString.substring(0,2); return new String("ab"); }
這裏最好不要寫成下面這樣,由於在JVM中存在字符串常量池,」ab」不會從新建立新字符串,全部的變量都會引用一個對象,而使用new String()則每次從新建立對象。
String getString() { return "ab"; }
關於字符串常量池,之後的文章會有介紹。
吐血推薦
若是你對本文這樣的內容感興趣,能夠閱讀如下Joshua Bloch大神寫得書,雖然有點貴,仍是英文的。 Java Puzzlers