一、Integer类的缓存机制

我们查看Integer的源码,就会发现里面有个静态内部类。

    public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
//当前值在缓存数组区间段,则直接返回该缓存值
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
//否则创建新的Integer实例
return new Integer(i);
} private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[]; //IntegerCache初始化时,缓存数值为-128-127的Integer实例(默认是从-128到127)。
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) {
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);
}
high = h; cache = new Integer[(high - low) + 1];
int j = low;
//填充缓存数组
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
} private IntegerCache() {}
}

该类的作用是将数值等于-128-127(默认)区间的Integer实例缓存到cache数组中。通过valueOf()方法很明显发现,当再次创建值在-128-127区间的Integer实例时,会复用缓存中的实例,也就是直接指向缓存中的Integer实例。

(注意:这里的创建不包括用new创建,new创建对象不会复用缓存实例,通过情景3的运行结果就可以得知)

二、其它具有缓存机制的类

实际上不仅仅Integer具有缓存机制,Byte、Short、Long、Character都具有缓存机制。来看看Long类中的缓存类

    private static class LongCache {
private LongCache(){} static final Long cache[] = new Long[-(-128) + 127 + 1]; static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}

ByteCache用于缓存Byte对象,ShortCache用于缓存Short对象,LongCache用于缓存Long对象,CharacterCache用于缓存Character对象。这些类都有缓存的范围,其中Byte,Short,Integer,Long为 -128 到 127,Character范围为 0 到 127。除了 Integer 可以通过参数改变范围外,其它的都不行。

面试题

面试题1:

    //情景1
Integer c = 128;
Integer d = 128;
System.out.println(c == d);//false //情景2
Integer a = 1;
Integer b = 1;
System.out.println(a == b);//true。b.intValue() //情景3
Integer e = new Integer(1);
Integer f = new Integer(1);
System.out.println(e == f);//false

面试题2:

    //情景4
int a = 1;
Integer b = Integer.valueOf(1);
Integer c = new Integer(1); System.out.println(a == b);//true
System.out.println(a == c);//true

分析:a是基本类型,b和c是引用类型,两者进行比较时有一个拆箱的过程,也就是会默认调用b和c的intValue()方法。

//拆箱
public int intValue() {
return value;
}

最终比较的是基本类型的值,自然是相等的。

面试题3:

//代码来源于《深入理解Java虚拟机》第4章4.3.1 P121。
public class SynAddRunnable implements Runnable { int a, b; public SynAddRunnable(int a, int b) {
this.a = a;
this.b = b;
} @Override
public void run() {
synchronized (Integer.valueOf(a)) {
synchronized (Integer.valueOf(b)) {
System.out.println(a + b);
}
}
} public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new SynAddRunnable(1, 2)).start();
new Thread(new SynAddRunnable(2, 1)).start();
}
}
}

上面这段程序会发生死锁。造成死锁的原因:[-128,127]之间的数字会被缓存,而Integer.valueOf()会返回缓存的对象。因此代码中200次for循环实际上总共只创建了两个对象,当线程A持有Integer.valueOf(1)时,如果线程B持有Integer.valueOf(2),则就会出现死锁,属于动态锁顺序死锁

总结

1.具有缓存机制的类?

Byte、Short、Integer、Long、Character都具有缓存机制。缓存工作都是在静态块中完成,在类生命周期(loading verify prepare resolving initial using unload)的初始化阶段执行。

2.缓存范围?

Byte,Short,Integer,Long为 -128 到 127

Character范围为 0 到 127

除了Integer可以指定缓存范围,其它类都不行。Integer的缓存上界high可以通过jvm参数-XX:AutoBoxCacheMax=size指定,取指定值与127的最大值并且不超过Integer表示范围,而下界low不能指定,只能为-128。

Integer类的缓存机制的更多相关文章

  1. Hibernate第二天——实体类 与缓存机制

    第二天,我们先来了解一下框架里的一个重要概念:实体类 实体类:把数据表或其它持久化数据的格式映射成的类,就是实体类. 实体类的编写规则:由于对应的是javabean,因而也遵循javabean的一些规 ...

  2. Integer类之缓存

    在开始详细的说明问题之前,我们先看一段代码 1 public static void compare1(){ 2 Integer i1 = 127, i2 = 127, i3 = 128, i4 = ...

  3. java Integer类的缓存(转)

    首先看一段代码(使用JDK 5),如下: public class Hello { public static void main(String[] args) { int a = 1000, b = ...

  4. Java Integer类的缓存

    首先看一段代码(使用JDK 5),如下: public class Hello { public static void main(String[] args) { int a = 1000, b = ...

  5. Integer缓存机制-基本数据类型和包装类型-自动拆装箱

    Integer缓存机制 总结: 1.jdk1.5对Integer新增了缓存机制,范围在-128-127(这个范围的整数值使用频率最高)内的自动装箱返回的是缓存对象,不会new新的对象,所以只要在缓存范 ...

  6. 闲谈关于discuz内核缓存机制

    Discuz! 缓存 Discuz! X2.5 的 config_global.php 中有这样一行代码 $_config['cache']['type'] = 'sql'; 这就是 Discuz! ...

  7. java中字面量,常量和变量之间的区别(附:Integer缓存机制)

    一.引子 在各种教科书和博客中这三者经常被引用,今天复习到内存区域,想起常量池中就是存着字面量和符号引用,其实这三者并不是只在java中才有,各个语言中都有类似的定义,所以做一下总结,以示区分. 二. ...

  8. Java的自动拆装箱与Integer的缓存机制

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10832303.html 一:基本类型与包装类型     我们知道,Java有8大基本数据类型,4整2浮1符1 ...

  9. Integer的缓存机制

    Java api 中为了提高效率,减少资源的浪费,对内部的Integer类进行了缓存的优化,通俗的说就是把-127至128这个范围内的数提前加载到内存,当我们需要的时候,如果正好在这个范围之内,就会直 ...

随机推荐

  1. Java中使用Redis的几种数据类型总结

    1.String,最基本的类型 方法  set.get 2.hash redis 127.0.0.1:6379> HMSET user:1 username redis.net.cn passw ...

  2. <foreach></foreach>标签

    当传入参数为数组或者集合时需要通过<foreach></foreach>标签进行遍历 1.首先在po类中定义一个集合或者数组 比如 private List<Intege ...

  3. db2数据库表操作错误SQL0668N Operation not allowed for reason code "1" on table "表". SQLSTATE=57016的解决方法

    错误sql Operation not allowed for reason code "1" on table "MARKET.PURE_USER".. SQ ...

  4. 克隆虚拟机启动网卡提示错误 Device eth0 does not seem to be present, delaying initialization

    错误原因: 克隆的Linux系统在新的机器上运行,新服务器网卡物理地址已经改变.而/etc/udev/rules.d/70-persistent-net.rules这个文件确定了网卡和MAC地址的信息 ...

  5. Android animation summary

    Android animation 动画定义 动画的意思就是一连串画面动起来了,根据这一连串画面的产生原理可分为两类:补间动画(Tween animation)和帧动画(frame animation ...

  6. lazyload懒加载插件

    在main.js中引入vue-lazyload插件  并使用 注册插件: import VueLazyLoad from 'vue-lazyload' Vue.use(VueLazyLoad,{ lo ...

  7. 007-elasticsearch5.4.3【一】概述、Elasticsearch 访问方式、Elasticsearch 面向文档、常用概念

    一.概述 Elasticsearch 是一个开源的搜索引擎,建立在一个全文搜索引擎库 Apache Lucene™ 基础之上. Elasticsearch 也是使用 Java 编写的,它的内部使用 L ...

  8. PHP 常用函数-url函数

    urlencode 和 rawurlencode urlencode 和 rawurlencode 两个函数都用来编码 URL 字符串.除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后 ...

  9. vue组件间通信子与父

    二.组件间通信(子组件传值给父组件) 通过事件的方式来完成数据的传输. ①在父组件中 定义一个方法,用来接收子组件所通过事件传来的值 methods:{ recvMsg:function(msg){ ...

  10. jmeter模拟spike尖峰测

    jmeter模拟spike尖峰测试 概述 尖峰测试(Spike testing)在性能测试中属于压力测试的一个子集.指的是在某一瞬间或者多个频次下用户数和压力陡然增加的场景. 为了验证我们的网站在访问 ...