Objects become eligible for garbage collection (GC) if they are no longer reachable by the main entry point(s) in a program. GC is usually not performed explicitly by the user, but to let the GC know an object is no longer needed a developer can:
Dereference / assign null
someFunction {
var a = 1;
var b = 2;
a = null; // GC can now free the memory used for variable a
...
} // local variable b not dereferenced but will be subject to GC when function ends
Use weak references
Most languages with GC allow you to create weak references to an object which do not count as a reference for the GC. If there are only weak references to an object and no strong (normal) references, then the object is eligible for GC.
WeakReference wr = new WeakReference(createSomeObject());
Note that after this code it is dangerous to use the target of the weak reference without checking if the object still exists. Beginner-programmers sometimes make the mistake of using code like this:
if wr.target is not null {
doSomeAction(wr.target);
}
This can cause problems because GC may have been invoked after the null check and before the execution of doSomeAction. It's better to first create a (temporary) strong reference to the object like this:
Object strongRef = wr.target;
if strongRef is not null {
doSomeAction(strongRef);
}
strongRef = null;