在Java的api中,对于Integer的cache了-127~128的数据。
在方法valuesOf()中,实现如下
Cache数据的两种时机:public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
- 使用的时候,用到的时候先从cache里取,有直接取,没有创建,然后放入cache里。
- 一些大的数据类,创建和使用成本都很高,使用懒汉式加载策略。
- 加载的时候自动创建
- 数据本身比较小,构造的成本比较小,可以使用饿汉式加载,即在static 代码块里完成了初始化工作。
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 //... cache = new Integer[(high - low) + 1]; int j = low; for (int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() { } }