参考源代码,value是final类型的,不可变。
private final int value;
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);
}
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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
看看如下代码的运行结果:
public static void main(String[] args) {
Integer a = 10;
Integer b = 10;
System.out.println("a == b " + (a == b));
System.out.println("a.equals(b) " + (a.equals(b)));
a = new Integer(10);
b = new Integer(10);
System.out.println("a == b " + (a == b));
System.out.println("a.equals(b) " + (a.equals(b)));
a = 166;
b = 166;
System.out.println("a == b " + (a == b));
System.out.println("a.equals(b) " + (a.equals(b)));
}
结果如下:
a==b true a.equals(b) true 解释: -128~127之间的数值,从cache中提取
a==b false a.equals(b) true 解释: new Integer(10)分配新内存
a==b false a.equals(b) true 解释:超过127的数据,重新分配内存
不可变对象,不要使用同步锁,如下代码不可靠,应该使用Object obj:
Integer aa = 100;
synchronized(aa){
}
如果aa的值发生变化,如aa=102,而aa指向新的对象,原来锁定的代码块失去同步的意义了。