cache pool에 대해 설명한다.
autoboxing으로 -128 ~ 127의 숫자의 참조타입으로 변환할 때, Integer 캐싱풀에 동일한 정수 객체가 있다면, 캐싱풀의 객체를 사용한다.
예를 들면, Integer.valueOf()를 사용할 때 발생한다.
Integer 클래스는 내부적으로 정적 캐싱 배열을 사용하여 캐싱 풀을 관리한다. 소스 코드를 보면, 캐싱 풀은 정적 블록에서 초기화된다.
이 배열(cache)은 힙 메모리에 저장되며, Integer.valueOf() 메서드가 이를 활용한다.
// -128~127 정수를 autoboxing 할 때 캐싱 풀의 객체를 참조한다.
Integer c = Integer.valueOf(10);
Integer d = Integer.valueOf(10);
System.out.println(c == d); // true
// Integer 생성자 사용 -> 다른 객체로 저장
Integer c1 = new Integer(10);
Integer d1 = new Integer(10);
System.out.println(c1 == d1); // false (캐싱된 동일 객체)
Integer Cache class
Integer 클래스의 inner class로 존재하는 Integer Cache class에서 -128~127의 정수를 정적 배열로 관리한다.
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
CDS.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
문자열 리터럴이 동일하다면 String 객체를 공유해서 사용한다.
힙 영역의 String Constant Pool에 저장된다. 이 풀은 JVM이 힙 영역 내에서 특별히 관리하는 공간으로, 동일한 문자열 리터럴을 공유하도록 설계되었다.
// 문자열 리터럴 사용 -> 캐싱 풀의 객체를 사용
String a = "abc";
String b = "abc";
System.out.println(a == b); // true
// String 생성자 사용 -> 다른 객체로 저장
String a1 = new String("abc");
String b1 = new String("abc");
System.out.println(a1 == b1); // false
참고자료
https://stackoverflow.com/questions/3801343/what-is-string-pool-in-java
https://velog.io/@rivkode/Integer-cache-pool-Java-%EB%B3%80%EC%88%98-%ED%95%A0%EB%8B%B9
https://woonys.tistory.com/221