学习JDK源码(二):Integer

最近没有好好保持学习的好习惯,该打。

天天忙,感觉都不知道在干嘛。真的厌倦了普通的Java代码,还是想学点新技术。

用了这么久的Java,最常用的数据类型肯定是Int了,而他的包装类Integer用的其实也不少。但是问问我们自己,当我们创建一个数字对象时,你们是直接new int x =1的多吧,或者说用new Integer(1),其实这样写的已经就很少了,我就没怎么这么写过。直到最近,我才知道一个能提升性能的方法Integer.valueOf(1),他可以使用系统缓存,既能减少可能的内存占用,也省去了频繁创建对象的开销。 

1 public static Integer valueOf(int i) {  
2     assert IntegerCache.high >= 127;  
3     if (i >= IntegerCache.low && i <= IntegerCache.high)  
4         return IntegerCache.cache[i + (-IntegerCache.low)];  
5     return new Integer(i);  
6 }  

看下上面的valueOf的源码,关键在于return那里,其实这里看不出什么,再往深层看:

 1 private static class IntegerCache {  
 2     static final int low = -128;  
 3     static final int high;  
 4     static final Integer cache[];  
 5   
 6     static {  
 7         // high value may be configured by property  
 8         int h = 127;  
 9         String integerCacheHighPropValue =  
10             sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");  
11         if (integerCacheHighPropValue != null) {  
12             int i = parseInt(integerCacheHighPropValue);  
13             i = Math.max(i, 127);  
14             // Maximum array size is Integer.MAX_VALUE  
15             h = Math.min(i, Integer.MAX_VALUE - (-low) -1);  
16         }  
17         high = h;  
18   
19         cache = new Integer[(high - low) + 1];  
20         int j = low;  
21         for(int k = 0; k < cache.length; k++)  
22             cache[k] = new Integer(j++);  
23     }  
24   
25     private IntegerCache() {}  
26 }  

它为 -128 ~ 127 数值提供自动装箱的缓存服务,明显速度能有提升

static 静态代码块可知缓存的初始化是在第一次使用的时候。 通过 VM 参数-XX:AutoBoxCacheMax=<size> 可以配置缓存的最大值。 在 VM 初始化期间, 缓存最大值 high, 可能被保存在 sun.misc.VM class 的私有系统属性里。      

原文地址:https://www.cnblogs.com/timePasser-leoli/p/8244652.html