As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.
Garbage Collection succeeds in allocating objects efficiently on the heap memory using the generations of garbage collection. Manual freeing of memory is not needed as garbage collection automatically releases the memory space after it is no longer required.
Smart pointers are one of the least efficient forms of garbage collection, particularly in the context of multi-threaded applications when reference counts are bumped atomically.
When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots.
I'd like to allocate an array of elements from the garbage collected heap, and access those elements only through raw pointers. Is the garbage collector capable of reclaiming that block of memory after (and not before) all the pointers that used to point to it have gone out of scope?
I was thinking of doing it like this:
{
int* ptrToArray1 = (new int[](100)).ptr;
int* ptrToArray2 = ptrToArray1;
int* ptrToArray3 = ptrToArray1 + 10;
ptrToArray1 += 50;
ptrToArray2 += 99;
*ptrToArray1 = 123;
*ptrToArray2 = 456;
*ptrToArray3 = 789;
ptrToArray1 -= 42;
ptrToArray2 -= 24;
//... and so on ... Is the array data guaranteed to be there?
}
// Now that all the pointers are out of scope, can the
// garbage collector reclaim the memory block of that array?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With