Suppose we take a sample code as below
class Employee
{
int id;
String name;
}
Employee e = new Employee(1, "NewEmployee");
In the above code, I'm assuming the allocation of heap memory for Employee Object happens first and then its reference is assigned to the stack reference e
.
Is the above valid or something deep happens here?
If Yes, Then lets assume right after the memory creation in heap and just before its reference is assigned to e
, a GC kicks in and identifies there are no references to this new Heap memory from GC roots.
- Would GC Clean this resource up?
- Is there a way JVM/CLR handles these scenario's and avoid this kind of Memory corruption?
Tagging both Java & C#, as I see the logic of cleaning up in case of Mark and Sweep for both Java and C# seems to be almost same (at least in terms of identifying unused object from roots & cleaning up).