Java Basics  «Prev  Next»

Lesson 8Reclaiming memory via Garbage Collection
ObjectiveBe able to briefly describe how Java reclaims memory.

Reclaiming Memory via Garbage Collection

Java takes over responsibility for managing memory in the runtime environment by providing garbage collection.

What is garbage collection?

When you create a new object using new, you are asking the Java runtime to allocate memory to maintain this object. However, nowhere have you stated exactly how much memory Java needs to allocate. And it's never necessary to tell Java to release the memory. Memory management is Java's responsibility.

Garbage collection:

Java's way of reclaiming memory that your program has allocated at some point during its execution but can no longer access.
The ability to reclaim memory that your program can no longer access is known as garbage collection. The mechanism responsible for garbage collection runs continually as a separate thread.
This way, Java can continually check for memory that should be reclaimed.

Example

The objects reclaimed are those that you can no longer access from a program.
For example, take a look at the following snippet:

String s = new String("test");
// . . . use s for a while . . .
s = null;

As soon as the variable s is set to null (which indicates there is no object that s currently references), there is no way for your program to access the String instance you allocated.
Java recognizes this object is a candidate for garbage collection and will reclaim and use this memory for other objects if it runs out of space.
Next, let's examine how Java uses mark and sweep to perform garbage collection.

Consider the following code:
class MyClass { }
public class TestClass {
 MyClass getMyClassObject() {
  MyClass mc = new MyClass(); // 1          
  return mc; // 2    
}
 public static void main(String[] args) {
  TestClass tc = new TestClass();// 3       
  MyClass x = tc.getMyClassObject(); // 4       
  System.out.println("got myclass object"); // 5       
  x = new MyClass(); // 6       
  System.out.println("done"); // 7    
 }
}

After what line will the MyClass object created at line 1 be eligible for garbage collection?
Select 1 option
  1. 2
  2. 5
  3. 6
  4. 7
  5. Never till the program ends.


Answer: c
Explanation:
c) At line 6, x starts pointing to a new MyClassObject and no reference to the original MyClass object is left. Garbage Collection:
Although not mentioned explicitly in the objectives, the exam 1Z0-803 has a few basic questions on garbage collection.
All you need to know is:
  1. An object can be made eligible for garbage collection by making sure there are no references pointing to that object.
  2. You cannot directly invoke the garbage collector. You can suggest the JVM to perform garbage collection by calling System.gc();