乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Java中的substring真的會(huì)引起內(nèi)存泄露么?

       月影曉風(fēng) 2015-09-28

      在Java中開發(fā),String是我們開發(fā)程序可以說必須要使用的類型,String有一個(gè)substring方法用來截取字符串,我們想必也常常使用。但是你知道么,關(guān)于Java 6中的substring是否會(huì)引起內(nèi)存泄露,在國(guó)外的論壇和社區(qū)有著一些討論,以至于Java官方已經(jīng)將其標(biāo)記成bug,并且為此Java 7 還重新進(jìn)行了實(shí)現(xiàn)。讀到這里可能你的問題就來了,substring怎么會(huì)引起內(nèi)存泄露呢?那么我們就帶著問題,走進(jìn)小黑屋,看看substring有沒有內(nèi)存泄露,又是怎么導(dǎo)致所謂的內(nèi)存泄露。

      基本介紹

      substring方法提供兩種重載,第一種為只接受開始截取位置一個(gè)參數(shù)的方法。

      1
      
      public String substring(int beginIndex)
      

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

      另一種重載就是接受一個(gè)開始截取位置和一個(gè)結(jié)束截取位置的參數(shù)的方法。

      1
      
      public String substring(int beginIndex, int endIndex)
      

      使用這個(gè)方法,"smiles".substring(1, 5) 返回結(jié)果 "mile"

      通過這個(gè)介紹我們基本了解了substring的作用,這樣便于我們理解下面的內(nèi)容。

      準(zhǔn)備工作

      因?yàn)檫@個(gè)問題出現(xiàn)的情況在Java 6,如果你的Java版本號(hào)不是Java 6 需要調(diào)整一下。

      終端調(diào)整(適用于Mac系統(tǒng))

      查看java版本號(hào)

      1
      2
      3
      4
      
      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

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

      Ubuntu使用alternatives --config java,F(xiàn)edora上面使用alternatives --config java。

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

      問題重現(xiàn)

      這里貼一下java官方bug里用到的重現(xiàn)問題的代碼。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      
      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 都不會(huì)拋出異常)運(yùn)行一下就會(huì)報(bào)java.lang.OutOfMemoryError: Java heap space的異常,這說明沒有足夠的堆內(nèi)存供我們創(chuàng)建對(duì)象,JVM選擇了拋出異常操作。

      于是有人會(huì)說,是因?yàn)槟忝總€(gè)循環(huán)中創(chuàng)建了一個(gè)TestGC對(duì)象,雖然我們加入ArrayList只是兩個(gè)字符的字符串,但是這個(gè)對(duì)象中又存儲(chǔ)largeString這么大的對(duì)象,這樣必然會(huì)造成OOM的。

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

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      
      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());
              }
      
          }
      }
      

      執(zhí)行上面的方法,并不會(huì)導(dǎo)致OOM異常,因?yàn)槲覀兂钟械臅r(shí)1000000個(gè)ab字符串對(duì)象,而TestGC對(duì)象(包括其中的largeString)會(huì)在java的垃圾回收中釋放掉。所以這里不會(huì)存在內(nèi)存溢出。

      那么究竟是什么導(dǎo)致的內(nèi)存泄露呢?要研究這個(gè)問題,我們需要看一下方法的實(shí)現(xiàn),即可。

      深入Java 6實(shí)現(xiàn)

      在String類中存在這樣三個(gè)屬性

      • value 字符數(shù)組,存儲(chǔ)字符串實(shí)際的內(nèi)容
      • offset 該字符串在字符數(shù)組value中的起始位置
      • count 字符串包含的字符的長(zhǎng)度

      Java 6中substring的實(shí)現(xiàn)

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      
      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);
      }
      

      上述方法調(diào)用的構(gòu)造方法

      1
      2
      3
      4
      5
      6
      
      //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;
      }
      

      當(dāng)我們讀完上述的代碼,我們應(yīng)該會(huì)豁然開朗,原來是這個(gè)樣子啊!

      當(dāng)我們調(diào)用字符串a(chǎn)的substring得到字符串b,其實(shí)這個(gè)操作,無非就是調(diào)整了一下b的offset和count,用到的內(nèi)容還是a之前的value字符數(shù)組,并沒有重新創(chuàng)建新的專屬于b的內(nèi)容字符數(shù)組。

      舉個(gè)和上面重現(xiàn)代碼相關(guān)的例子,比如我們有一個(gè)1G的字符串a(chǎn),我們使用substring(0,2)得到了一個(gè)只有兩個(gè)字符的字符串b,如果b的生命周期要長(zhǎng)于a或者手動(dòng)設(shè)置a為null,當(dāng)垃圾回收進(jìn)行后,a被回收掉,b沒有回收掉,那么這1G的內(nèi)存占用依舊存在,因?yàn)閎持有這1G大小的字符數(shù)組的引用。

      看到這里,大家應(yīng)該可以明白上面的代碼為什么出現(xiàn)內(nèi)存溢出了。

      共享內(nèi)容字符數(shù)組

      其實(shí)substring中生成的字符串與原字符串共享內(nèi)容數(shù)組是一個(gè)很棒的設(shè)計(jì),這樣避免了每次進(jìn)行substring重新進(jìn)行字符數(shù)組復(fù)制。正如其文檔說明的,共享內(nèi)容字符數(shù)組為了就是速度。但是對(duì)于本例中的問題,共享內(nèi)容字符數(shù)組顯得有點(diǎn)蹩腳。

      如何解決

      對(duì)于之前比較不常見的1G字符串只截取2個(gè)字符的情況可以使用下面的代碼,這樣的話,就不會(huì)持有1G字符串的內(nèi)容數(shù)組引用了。

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

      下面的這個(gè)構(gòu)造方法,在源字符串內(nèi)容數(shù)組長(zhǎng)度大于字符串長(zhǎng)度時(shí),進(jìn)行數(shù)組復(fù)制,新的字符串會(huì)創(chuàng)建一個(gè)只包含源字符串內(nèi)容的字符數(shù)組。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      
      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 實(shí)現(xiàn)

      在Java 7 中substring的實(shí)現(xiàn)拋棄了之前的內(nèi)容字符數(shù)組共享的機(jī)制,對(duì)于子字符串(自身除外)采用了數(shù)組復(fù)制實(shí)現(xiàn)單個(gè)字符串持有自己的應(yīng)該擁有的內(nèi)容。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      
      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方法中調(diào)用的構(gòu)造方法,進(jìn)行內(nèi)容字符數(shù)組復(fù)制。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      
      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);
      }
      

      真的是內(nèi)存泄露么

      我們知道了substring某些情況下可能引起內(nèi)存問題,但是這個(gè)叫做內(nèi)存泄露么?

      其實(shí)個(gè)人認(rèn)為這個(gè)不應(yīng)該算為內(nèi)存泄露,使用substring生成的字符串b固然會(huì)持有原有字符串a(chǎn)的內(nèi)容數(shù)組引用,但是當(dāng)a和b都被回收之后,該字符數(shù)組的內(nèi)容也是可以被垃圾回收掉的。

      哪個(gè)版本實(shí)現(xiàn)的好

      關(guān)于Java 7 對(duì)substring做的修改,收到了褒貶不一的反饋。

      個(gè)人更加傾向于Java 6的實(shí)現(xiàn),當(dāng)進(jìn)行substring時(shí),使用共享內(nèi)容字符數(shù)組,速度會(huì)更快,不用重新申請(qǐng)內(nèi)存。雖然有可能出現(xiàn)本文中的內(nèi)存性能問題,但也是有方法可以解決的。

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

      問題的價(jià)值

      雖然這個(gè)問題出現(xiàn)在Java 6并且Java 7中已經(jīng)修復(fù),但并不代表我們就不需要了解,況且Java 7的重新實(shí)現(xiàn)被噴的很厲害。

      其實(shí)這個(gè)問題的價(jià)值,還是比較寶貴的,尤其是內(nèi)容字符數(shù)組共享這個(gè)優(yōu)化的實(shí)現(xiàn)。希望可以為大家以后的設(shè)計(jì)實(shí)現(xiàn)提供幫助和一些想法。

      受影響的方法

      trim和subSequence都存在調(diào)用substring的操作。Java 6和Java 7 substring實(shí)現(xiàn)的更改也間接影響到了這些方法。

      參考資源

      以下三篇文章寫得都比較不錯(cuò),但是都稍微有一些問題,我都已經(jīng)標(biāo)明出來,大家閱讀時(shí),需要注意。

      注意

      上面的重現(xiàn)問題的代碼中

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

      這里最好不要寫成下面這樣,因?yàn)樵贘VM中存在字符串常量池,”ab”不會(huì)重新創(chuàng)建新字符串,所有的變量都會(huì)引用一個(gè)對(duì)象,而使用new String()則每次重新創(chuàng)建對(duì)象。

      1
      2
      3
      
      String getString() {
            return "ab";
      }
      

      關(guān)于字符串常量池,以后的文章會(huì)有介紹。

      吐血推薦

      如果你對(duì)本文這樣的內(nèi)容感興趣,可以閱讀以下Joshua Bloch大神寫得書,雖然有點(diǎn)貴,還是英文的。 Java Puzzlers

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多