パッケージクラスキャッシュの問題

2674 ワード

整数型、char型に対応するパッケージ類は、自動梱包時に-128~127の値に対してキャッシュ処理を行い、効率を向上させることを目的としている.
          :     -128~127    ,                        ,   256          cache    。           (      valueOf() ),             ,                      ,       ,    new               。

       Integer   ,   Java        ,          ,   8-7  。

【例8-7】Integerクラス関連ソースコードは以下の通りである.
public static Integer valueOf(int i){if(i>=IntegerCache.low&&i<=IntegerCache.high)return IntegerCache.cache[i+(-integerCache.low)];return new Integer(i)}このコードでは、次のいくつかの問題を説明する必要があります.
  1. IntegerCache  Integer         ,  Integer   。

  2.       IntegerCache.low -128,IntegerCache.high 127,IntegerCache.cache           ,   8-8  。

【例8-8】IntegerCacheクラス関連ソースコードは以下の通りである.
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static {//high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty(“java.lang.Integer.IntegerCache.high”); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127);//Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) {//If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++);
    // range [-128, 127] must be interned (JLS7 5.1.7)
    assert IntegerCache.high >= 127;
}
private IntegerCache() {}

}上記のソースコードから、静的コードブロックの目的は配列cacheを初期化することであり、このプロセスはクラスロード時に完了することがわかります.
             ,   8-9  。

【例8-9】テストコード
public class Test 3{public static void main(String[]args){Inteeger in 1=-128;Inteeger in 2=-128;System.out.println(in 1==in 2);///true 123はキャッシュ範囲内でSystem.out.println(in 1.equals(in 2);///true Inteeger in 3=1234;Inteeger in 4=1234;System.out.println(in 3==in 4);///false 1234は1234でないため1234;Inteeger in 4=1234;Inteeger in 4;System.out.println(in 3==in 4);///false e e e e e eキャッシュ範囲内System.out.println(in 3.equals(in 4);//true}}実行結果を図8-6に示す.
図8-6例8-9運転効果図.png
図8-6例8-9運転効果図
    8-9       8-7  :

図8-7例8-9のメモリ解析図.png
図8-7例8-9のメモリ分析図
に注意
  1. JDK1.5  ,            , :

Integer i=100;int j=new Integer(100);2.自動梱包はnew Integer()メソッドではなくvalueOf()メソッドを呼び出します.
  3.        xxxValue()  。

  4.                ,  -128~127           。     ,         ==       ,    equals  。