温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Integer IntegerCache源码的示例分析

发布时间:2021-09-09 10:03:39 来源:亿速云 阅读:91 作者:小新 栏目:编程语言

这篇文章主要介绍Integer IntegerCache源码的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

先看一段测试结果:

/*public static void main(String[] args) {
    Integer a = 128, b = 128;
    Integer c = 127, d = 127;
    System.out.println(a == b);//false
    System.out.println(c == d);//true

  }*/
  
  /*public static void main(String[] args) {
    Integer int1 = Integer.valueOf("100");
    Integer int2 = Integer.valueOf("100");
    System.out.println(int1 == int2);//true
  }*/

  public static void main(String[] args) {
    Integer int1 = Integer.valueOf("300");
    Integer int2 = Integer.valueOf("300");
    System.out.println(int1 == int2);//false
  }

JDK的源码如下:

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
  }

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
      return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
  }

发现里面另有玄机,多了个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() {}
  }

原来Integer把-128到127(可调)的整数都提前实例化了。

这就解释了答案,原来你不管创建多少个这个范围内的Integer用ValueOf出来的都是同一个对象。

但是为什么JDK要这么多此一举呢? 我们仔细想想, 淘宝的商品大多数都是100以内的价格, 一天后台服务器会new多少个这个的Integer, 用了IntegerCache,就减少了new的时间也就提升了效率。同时JDK还提供cache中high值得可配置,

这无疑提高了灵活性,方便对JVM进行优化。

以上是“Integer IntegerCache源码的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI