In a language like C++, the application program is responsible for managing the memory used by dynamically allocated memory. When an object is created in the C++ heap using the new
operator, there needs to be a corresponding use of the delete
operator to dispose of the object:
delete
an object and just “forgets” about it, the associated memory is lost to the application. The term for this situation is a memory leak, and it too much memory leaks an application is liable to use more and more memory, and eventually crash.delete
the same object twice, or use an object after it has been deleted, then the application is liable to crash due to problems with memory corruptionIn a complicated C++ program, implementing memory management using new
and delete
can be time consuming. Indeed, memory management is a common source of bugs.
Java takes a different approach. Instead of an explicit delete
operator, Java provides an automatic mechanism known as garbage collection to reclaim the memory used by objects that are no longer needed. The Java runtime system takes responsibility for finding the objects to be disposed of. This task is performed by a component called a garbage collector, or GC for short.
At any time during the execution of a Java program, we can divide the set of all existing objects into two distinct subsets1:
> A reachable object is any object that can be accessed in any potential continuing computation from any live thread.
In practice, this means that there is a chain of references starting from an in-scope local variable or a `static` variable by which some code might be able to reach the object.
Any objects that are unreachable are eligible for garbage collection. This does not mean that they will be garbage collected. In fact:
The Java language Specification gives a lot of latitude to a JVM implementation to decide when to collect unreachable objects. It also (in practice) gives permission for a JVM implementation to be conservative in how it detects unreachable objects.
The one thing that the JLS guarantees is that no reachable objects will ever be garbage collected.
First of all, nothing specifically happens when an object becomes unreachable. Things only happen when the garbage collector runs and it detects that the object is unreachable. Furthermore, it is common for a GC run to not detect all unreachable objects.
When the GC detects an unreachable object, the following events can occur.
Reference
objects that refer to the object, those references will be cleared before the object is deleted.