java中整数常量池(-128~127)上限如何调整?

众所周知:java中Integer有一个常量池范围-128~127

Integer a = 500, b = 500;
System.out.println(a == b);//false
a = 100;
b = 100;
System.out.println(a == b);//true

相信也有一部分人在面试时,也被问到过这个问题,但是如果面试官继续追问:如果我想让 

Integer a = 500, b = 500;
System.out.println(a == b);

也返回true,该怎么做?没准备的同学,可能会一时被问住,其实答案就在java.lang.Integer.IntegerCache 这个类的源码上

    /**
     * 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 {
       // ...
    }

这个类的注释上,已经明细说明:

-XX:AutoBoxCacheMax=<size>
-Djava.lang.Integer.IntegerCache.high=<size>

这2个参数都可以控制上限。

posted @ 2021-05-30 22:40  菩提树下的杨过  阅读(574)  评论(0编辑  收藏  举报