运行时常量池,class常量池,Integer常量池,字符串常量池是什么关系?

阅读<<深入理解Java虚拟机>>时,遇到了一个问题:

运行时常量池,class常量池,Integer常量池,字符串常量池是什么关系?

首先是运行时常量池,class常量池的联系:class常量池是属于类的,每个类都有一个class常量池,加载后就将其加入到运行时常量池(粗浅理解,还没看完);

Integer常量池和字符串常量池

字符串常量池是在堆中的,用到的是享元设计思想;

Integer常量池更准确说不应该叫整型常量池,而是叫缓存更合适:

由于查询书籍并未找到相关介绍,于是查看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() {}
}

应该有人英语跟我一样很吃力,注释翻译如下:

大概解读一下:

在这里插入图片描述

到这里我又迷糊了:这个数组是static final修饰的,如果按照一般理解,jvm虚拟机在完成类装载操作后,将class文件中的常量池载入到内存中,会保存在方法区中,但是这里的常量数组没有给默认值,默认的初始化值应该是null,然后new了一个数组对象对其赋值,那么这个数组应该是在堆里?迷糊了,不知道这个数组是在堆里还是在方法区里,有知道的可以留言告诉我答案…


挖坑,日后填…
未完待续

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值