Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After GC , the address of the object in memory be changed and why the object reference still valid?

Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap. New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Read more: http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html#ixzz2MeKK2gBA

So my question is that after these moving action , the address in memory should be changed and why the object reference still valid ?

like image 256
Mandy Mai Avatar asked Feb 17 '23 07:02

Mandy Mai


2 Answers

If the GC decides to move an object, it is its responsibility to update all references to that object.

This is transparent to the Java programmer: they can treat a reference as an abstract handle, and not worry about how the JVM manages object storage.

like image 108
NPE Avatar answered Apr 28 '23 11:04

NPE


Object references in Java are an abstract concept. They are not just integers representing memory offsets like C++ pointers. The Java Virtual Machine abstracts the access to the object it points to, so you don't have to worry about how the JVM manages its memory internally.

like image 28
Philipp Avatar answered Apr 28 '23 10:04

Philipp