Garbage Collection Flashcards
What is the heap ?
The heap is a memory area for dynamic allocation where objects are created and stored. It is managed by the garbage collector.
Dynamic memory allocation is the process of allocating memory at runtime, allowing a program to request and use memory as needed, rather than having a fixed amount allocated at compile time.
The garbage collector manages the heap by automatically identifying and reclaiming memory from objects that are no longer referenced, ensuring efficient memory use and preventing leaks.
What is the purpose of garbage collection ?
Garbage collection refers to the process of automatically freeing memory on the heap by
deleting objects that are no longer reachable in your program.
What is the characteristic of System.gc() ?
It meekly suggests that now might be a good time for Java to kick off a garbage collection run. Java is free to ignore the request.
When is an object no longer reachable ?
An object is no longer
reachable when one of two situations occurs:
■ The object no longer has any references pointing to it.
■ All references to the object have gone out of scope.
Give key characteristics that make a reference different than an object !
The reference is a variable that has a name and can be used to access the contents
of an object.
A reference can be assigned to another reference, passed to a method, or returned from a method. All references are the same size, no matter what their type is.
An object sits on the heap and does not have a name. Therefore, you have no way to
access an object except through a reference. Objects come in all different shapes and
sizes and consume varying amounts of memory
An object cannot be assigned to another object, nor can an object be passed to a method or returned from a method.
It is the object that gets garbage collected, not its reference.
Elaborate on the second case where an object may be garbage collected !
When a variable is declared within a method, it exists only for the duration of that method’s execution. Once the method completes, the variable goes out of scope, and any objects it referenced become unreachable if there are no other references pointing to them.
Similarly, if a variable is declared within a block (e.g., within curly braces), it is only accessible within that block.