오늘은 이펙티브 자바 중 "다 쓴 객체의 참조를 해제하라"
에 대한 내용을 포스팅하겠습니다.
먼저, 객체의 참조에 대해서 말씀드리겠습니다.
Foo foo = new Foo();
위 코드에서 foo는 Foo 객체의 참조 변수입니다. 즉, foo라는 참조 변수에 Foo 객체의 주소값이 들어가 있는 것 입니다.
쉽게 말해서, 참조라는 것은 어떤 객체나 배열 등의 주소값을 가지고 있는 것이라고 생각하면 될 것 같습니다.
Java에서는 객체 생성되고 사라질 때, 가비지 컬렉션이 사용됩니다. 가비지 컬렉터가 참조되지 않고 있는 객체들을 찾아서 제거해주는 것입니다.
하지만, 모든 객체가 다 가비지 컬렉터에 의해서 제거되는 것이 아닙니다.
//..위에 다른 코드
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // 다 쓴 객체 참조 해제
return result;
}
// 밑에 다른 코드
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
PostRepository postRepository = new PostRepository();
CacheKey key1 = new CacheKey(1);
postRepository.getPostById(key1);
Runnable removeOldCache = () -> {
Map<CacheKey, Post> cache = postRepository.getCache();
Set<CacheKey> cacheKeys = cache.keySet();
Optional<CacheKey> key = cacheKeys.stream().min(Comparator
.comparing(CacheKey::getCreated));
key.ifPresent((k) -> {
cache.remove(k);
}
);
reference
좋은 글 감사합니다. 자주 올게요 :)