java对象的缓存

来源:互联网 发布:域名绑定 编辑:程序博客网 时间:2024/06/05 05:41

先了看一段非常有意思的代码

public class TestIntegerCache {    public static void main(String[] args) {        Integer a = 12;        Integer b = 12;        System.out.println(a == b);//true        System.out.println("=========");        Integer x = 1222;        Integer y = 1222;        System.out.println(x == y);//false    }}

看到结果是不是有点意外呢,没关系我们看看编译过后的java代码什么样:

public class TestIntegerCache {    //自动创建一个空的构造函数    public TestIntegerCache() {    }    public static void main(String[] args) {      //注意此处调用了valueOf()方法,那这个方法是干嘛用的呢???        Integer a = Integer.valueOf(12);        Integer b = Integer.valueOf(12);        System.out.println(a == b);        System.out.println("=========");        Integer x = Integer.valueOf(1222);        Integer y = Integer.valueOf(1222);        System.out.println(x == y);    }}

我们打开Integer的源码:

 public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    } 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() {}    }

看到这里,相信各位看官都会恍然大悟,在类加载字节码文件的时候,会加载jvm配置,为了避免创建重复的对象,看到源码我们发现对Integer值做了缓存,创建对象的时候会判断这个值是否在这个范围内如果这个值在缓存-128~127范围内,直接返回缓存好的对象,否则new一个新的对象返回

原创粉丝点击