java整形中的缓存机制
英文原文:Java Integer Cache 翻译地址:Java中整型的缓存机制 原文作者:Java Papers 翻译作者:Hollis 转载请注明出处。
本文将介绍Java中Integer的缓存相关知识。这是在Java 5中引入的一个有助于节省内存、提高性能的功能。首先看一个使用Integer的示例代码,从中学习其缓存行为。接着我们将为什么这么实现以及他到底是如何实现的。你能猜出下面的Java程序的输出结果吗。如果你的结果和真正结果不一样,那么你就要好好看看本文了。
package com.javapapers.java;publicclassJavaIntegerCache{publicstaticvoid main(String... strings){Integer integer1 =3;Integer integer2 =3;if(integer1 == integer2)System.out.println("integer1 == integer2");elseSystem.out.println("integer1 != integer2");Integer integer3 =300;Integer integer4 =300;if(integer3 == integer4)System.out.println("integer3 == integer4");elseSystem.out.println("integer3 != integer4");}}
我们普遍认为上面的两个判断的结果都是false。虽然比较的值是相等的,但是由于比较的是对象,而对象的引用不一样,所以会认为两个if判断都是false的。在Java中,==比较的是对象应用,而equals比较的是值。所以,在这个例子中,不同的对象有不同的引用,所以在进行比较的时候都将返回false。奇怪的是,这里两个类似的if条件判断返回不同的布尔值。
上面这段代码真正的输出结果:
integer1 == integer2
integer3 != integer4
Java中Integer的缓存实现
在Java 5中,在Integer的操作上引入了一个新功能来节省内存和提高性能。整型对象通过使用相同的对象引用实现了缓存和重用。
适用于整数值区间-128 至 +127。
只适用于自动装箱。使用构造函数创建对象不适用。
Java的编译器把基本数据类型自动转换成封装类对象的过程叫做自动装箱,相当于使用valueOf方法:
Integer a =10;//this is autoboxingInteger b =Integer.valueOf(10);//under the hood
现在我们知道了这种机制在源码中哪里使用了,那么接下来我们就看看JDK中的valueOf方法。下面是JDK 1.8.0 build 25的实现:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/publicstaticInteger valueOf(int i){if(i >=IntegerCache.low && i <=IntegerCache.high)returnIntegerCache.cache[i +(-IntegerCache.low)];returnnewInteger(i);}
在创建对象之前先从IntegerCache.cache中寻找。如果没找到才使用new新建对象。
IntegerCache Class
IntegerCache是Integer类中定义的一个private static的内部类。接下来看看他的定义。
/**
* 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=} 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.
*/privatestaticclassIntegerCache{staticfinalint low =-128;staticfinalint high;staticfinalInteger cache[];static{// high value may be configured by propertyint 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 =newInteger[(high - low)+1];int j = low;for(int k =0; k < cache.length; k++)
cache[k]=newInteger(j++);// range [-128, 127] must be interned (JLS7 5.1.7)assertIntegerCache.high >=127;}privateIntegerCache(){}}
其中的javadoc详细的说明了缓存支持-128到127之间的自动装箱过程。最大值127可以通过-XX:AutoBoxCacheMax=size修改。 缓存通过一个for循环实现。从低到高并创建尽可能多的整数并存储在一个整数数组中。这个缓存会在Integer类第一次被使用的时候被初始化出来。以后,就可以使用缓存中包含的实例对象,而不是创建一个新的实例(在自动装箱的情况下)。
实际上这个功能在Java 5中引入的时候,范围是固定的-128 至 +127。后来在Java 6中,可以通过java.lang.Integer.IntegerCache.high设置最大值。这使我们可以根据应用程序的实际情况灵活地调整来提高性能。到底是什么原因选择这个-128到127范围呢?因为这个范围的数字是最被广泛使用的。 在程序中,第一次使用Integer的时候也需要一定的额外时间来初始化这个缓存。
Java语言规范中的缓存行为
在Boxing Conversion部分的Java语言规范(JLS)规定如下:
如果一个变量p的值是:
-128至127之间的整数(§3.10.1)
true 和 false的布尔值 (§3.10.3)
‘\u0000’至 ‘\u007f’之间的字符(§3.10.4)
中时,将p包装成a和b两个对象时,可以直接使用a==b判断a和b的值是否相等。
其他缓存的对象
这种缓存行为不仅适用于Integer对象。我们针对所有的整数类型的类都有类似的缓存机制。
有ByteCache用于缓存Byte对象
有ShortCache用于缓存Short对象
有LongCache用于缓存Long对象
有CharacterCache用于缓存Character对象
Byte, Short, Long有固定范围: -128 到 127。对于Character, 范围是 0 到 127。除了Integer以外,这个范围都不能改变。
【公告】版权声明
(全文完)
欢迎关注HollisChuang微信公众账号
如未加特殊说明,此网站文章均为原创,转载必须注明出处。HollisChuang's Blog » [译]Java中整型的缓存机制
java整形中的缓存机制的更多相关文章
- 02 java包装类型的缓存机制
02 java包装类型的缓存机制 Java 基本数据类型的包装类型的大部分都用到了缓存机制来提升性能. Byte,Short,Integer,Long 这 4 种包装类默认创建了数值 [-128,12 ...
- java项目中ehcache缓存最简单用法
java项目中ehcache缓存最简单用法: 1.下载ehcache-core-2.4.3.jar复制到项目的lib目录下 2.新建ehcache.xml文件,放置在项目src目录下的resour ...
- 解析Java分布式系统中的缓存架构(上)
作者 陈彩华 文章转载交流请联系 caison@aliyun.com 本文主要介绍大型分布式系统中缓存的相关理论,常见的缓存组件以及应用场景. 1 缓存概述 2 缓存的分类 缓存主要分为以下四类 2. ...
- hibernate中的缓存机制
一.为什么要用Hibernate缓存? Hibernate是一个持久层框架,经常访问物理数据库. 为了降低应用程序对物理数据源访问的频次,从而提高应用程序的运行性能. 缓存内的数据是对物理数据源中的数 ...
- php中ob缓存机制
1.ob缓存运行方式 2.注意:在程序中如果开启ob_start(),所有的echo输出都会保存到ob缓存中,可以使用ob系列函数进行操作,如果没有,默认情况下,在程序执行结束,会把缓存中的数据发送给 ...
- 分享知识-快乐自己:论Hibernate中的缓存机制
Hibernate缓存 缓存: 是计算机领域的概念,它介于应用程序和永久性数据存储源之间. 缓存: 一般人的理解是在内存中的一块空间,可以将二级缓存配置到硬盘.用白话来说,就是一个存储数据的容器.我们 ...
- 解决EF 4.0 中数据缓存机制
EF4.0默认开启缓存机制,如果想要禁用缓存机制的话,则须加上一句话:_db.CreateObjectSet().MergeOption = MergeOption.OverwriteChanges; ...
- 一次读懂mybatis中的缓存机制
缓存功能针对于查询(没听说果UPDATE,INSERT语句要缓存什么,都是直接执行的) 默认情况下,mybatis会启用一级缓存. 如果使用同一个session对象调用了相同的SELECT语句,则直接 ...
- Android 中的缓存机制与实现
Android开发本质上就是手机和互联网中的web服务器之间进行通信,就必然需要从服务端获取数据,而反复通过网络获取数据是比较耗时的,特别是访问比较多的时候,会极大影响了性能,Android中可通过二 ...
随机推荐
- linux上的mysql配置过程
自己阿里云上的服务器,记录下mysql的配置过程防止后面忘记 1. 首先用apt-get工具安装mysql sudo apt-get install mysql-server sudo apt-get ...
- centos7 --ngnix 常用命令:
配置命令 随服务器启动 # systemctl enable nginx.service 重启 nginx 服务 # systemctl restart nginx.service 停止 nginx ...
- 通过iLO进行Zabbix监控——针对HP服务器集成
iLO 全名是 Integrated Lights-out,它是惠普某些型号的服务器上集成的远程管理端口,它能够允许用户基于不同的操作系统从远端管理服务器,实现了虚拟存在和控制,从而进行智能型基础构架 ...
- [2017 ACL] 对话系统
Long Papers [Domain adaptation ] 1. Adversarial Adaptation of Synthetic or Stale Data ( Cited by 14 ...
- 07-matplotlib-箱线图
import numpy as np import matplotlib.pyplot as plt ''' 箱形图(Box-plot)又称为盒须图,盒式图,或 箱线图: 是一种用在显示一组数据分散情 ...
- 拒绝滥用golang defer机制
原文链接 : http://www.bugclosed.com/post/17 defer机制 go语言中的defer提供了在函数返回前执行操作的机制,在需要资源回收的场景非常方便易用(比如文件关闭, ...
- python中__name__属性的使用
python常用模块目录 1.打印出函数名字而非函数名对应的地址 )打印的是函数地址 def func(): print("我是%s函数"%func) func() ------- ...
- ssh软件及命令的使用
常用软件安装及使用目录 第1章 ssh常用用法小结 1.1 连接到远程主机: 命令格式 : ssh name@remoteserver 或者 ssh remoteserver -l name 说明:以 ...
- (转)Django 数据库
转:https://blog.csdn.net/ayhan_huang/article/details/77575186 目录 数据库说明 配置数据库 在屏幕输出orm操作对应的s ...
- 互评Beta版本——Thunder组爱阅app(探路者团队测评)
基于NABCD评论作品,及改进建议 每个小组评论其他小组beta发布的作品. 1.根据(不限于)NABCD评论作品的选题; N(Need,需求):在Beta中加入了书友QQ群,以及反馈建议,更好的 ...