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實現的更改也間接影響到了這些方法。
參考資源
以下三篇文章寫得都比較不錯,但是都稍微有一些問題,我都已經標明出來,大家閱讀時,需要注意。
- 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
原文鏈接:http://droidyue.com/blog/2014/12/14/substring-memory-issue-in-java/