JVM学习06:运行时数据区域-运行时常量池

这里写图片描述
这里写图片描述

基本描述
  • 运行时常量池是方法区的一部分;Class文件除了类信息、字段信息、方法信息、接口信息外还有一项信息是常量池(Constant Pool Table),用于存放编译期生成的各种字面量和符号引用,这部分内容将在类加载后进入方法区的运行时常量池中存放。
  • 运行时常量池相对于Class文件常量池的另外一个重要特征是具备动态性,Java语言并不要求常量一定只能在编译期产生,也就是并非预置入Class文件中常量池的内容才能进入方法区运行时常量池,运行期间也可能将新的常量放入池中,这种特性被开发人员利用得比较多的便是String类的intern()方法。
     * Returns a canonical representation for the string object.
     * <p>
     * A pool of strings, initially empty, is maintained privately by the
     * class {@code String}.
     * <p>
     * When the intern method is invoked, if the pool already contains a
     * string equal to this {@code String} object as determined by
     * the {@link #equals(Object)} method, then the string from the pool is
     * returned. Otherwise, this {@code String} object is added to the
     * pool and a reference to this {@code String} object is returned.
     * <p>
     * It follows that for any two strings {@code s} and {@code t},
     * {@code s.intern() == t.intern()} is {@code true}
     * if and only if {@code s.equals(t)} is {@code true}.
     * <p>
     * All literal strings and string-valued constant expressions are
     * interned. String literals are defined in section 3.10.5 of the
     * <cite>The Java&trade; Language Specification</cite>.
     *
     * @return  a string that has the same contents as this string, but is
     *          guaranteed to be from a pool of unique strings.
     */
    public native String intern();
  • 内存大小受限于方法区的大小,当常量池无法再申请到内存时会抛出OutOfMemoryError
  • 虽然虚拟机规范没有对常量池做严格的要求,但是一般除了保存Class文件中描述的符号引用,还会把翻译出来的直接引用存储在运行时常量池中。
类变量

被static修饰的变量,是类的一部分,由所有类实例共享。这些类变量只与类有关,因此他们总是作为类信息的一部分存储在方法区中。除了在类中声明的编译时常量外,虚拟机在使用某个类之前,都需要在方法区中为这些类变量分配空间。

编译时常量

被final修饰以及在编译时已知的值初始化的类变量。编译时常量和普通的类变量不同,每个使用编译时常量的类都会复制它的所有常量到自己的常量池中或嵌入自己的字节码流中。作为常量池或字节码的一部分,编译时常量保存在方法区中,就和一般的类变量一样,但是当一般的类变量作为声明他们类的一部分数据而保存的时候,编译时常量作为使用它们的类的一部分而保存。

转载于:https://my.oschina.net/sld880311/blog/1485950

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值