Garbage collection is automatic memory management by JVM.
If a Java object is unreachable (i.e. not accessible through any reference), then it is automatically released by the garbage collector.
An object becomes eligible for GC in one of the following cases:
Nullify the reference
MyClass obj = new MyClass();
obj = null;
Reassign the reference
MyClass obj = new MyClass();
obj = new MyClass();
Object created locally in a method
void method() {
MyClass obj = new MyClass();
// ...
}
GC is a background thread in JVM that runs periodically and reclaims memory of unreferenced objects.
Before an object is destroyed, its finalize()
method is invoked (if present).
One should override this method if the object holds any resource to be released explicitly, e.g., file close, database connection, etc.
class MyClass {
private Connection con;
public MyClass() throws Exception {
con = DriverManager.getConnection("url", "username", "password");
}
@Override
public void finalize() {
try {
if(con != null)
con.close();
} catch(Exception e) { }
}
}
class Main {
public static void method() throws Exception {
MyClass my = new MyClass();
my = null;
System.gc(); // request GC
}
// ...
}
System.gc();
Runtime.getRuntime().gc();
Hello.java --> Java Compiler --> Hello.class
javac Hello.java
.class --> JVM --> Windows (x86)
.class --> JVM --> Linux (ARM)