Integer缓存分析
2016-01-08 23:53
218 查看
当我们执行这样一条语句Integer i = 100; Java会做些什么事呢?
我们从源码分析,当我们给一个Integer对象赋一个int值的时候,自动装箱会调用Integer类的静态方法valueOf
IntegerCache是Integer的内部类
如果整型字面量的值在-128到127之间,那么不会new新的Integer对象,而是直接引用常量池中的Integer对象
我们从源码分析,当我们给一个Integer对象赋一个int值的时候,自动装箱会调用Integer类的静态方法valueOf
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
IntegerCache是Integer的内部类
/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ 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() {} }
如果整型字面量的值在-128到127之间,那么不会new新的Integer对象,而是直接引用常量池中的Integer对象
相关文章推荐
- 【学神-RHEL7】 P1-Python基础
- 开源框架SDWebImage的基本实现及思想
- Android Studio初体验(快捷键)
- Bootstrap 模态对话框只加载一次 remote 数据的解决办法
- 接口与抽象类的终极区别
- 【视频】Excel2013十大企业级明星函数视频课程【精讲】
- c#中绝对路径和相对路径
- BootStrap modal() 如何根据返回的HTML宽度自动调整宽度?
- 爱护你的眼睛请使用f.lux
- 理解Android虚拟机体系结构
- 如何搭建一个自己的网络验证系统?
- Adaboost的几个人脸检测网站
- caffe深度学习系列2015年12月
- Oracle Linux 教程 by 冰琉璃
- ListView下拉刷新
- JAVA中实现链式操作(方法链)的简单例子
- myeclipse导出可执行jar包读取外部配置文件
- 多益网址——开发者专用
- skyline代码搬迁后3d控件出错
- 关于智能时代革命性产品的构想--虚拟机器人