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.
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).
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
This is the wrong assumption, GC simply won't kick in in the middle of such assignment. Obviously, it would be incorrect and dangerous behavior.
And more generally, when JITtting methods, "safe-points" are injected where GC may kick in. Those are typically sub-methods calls, long loops and others (it strictly depend on JIT implementation).
Not sure about JVM but in case of CLR it is hard to see such "GCInfo" about safe-points, even if you will grab the generated assembly code (for example by using https://sharplab.io). I am not aware of any tool other than WinDbg to see it.