anathema
anathema

Reputation: 977

Garbage collection when application ends

As far as I know objects are available to be garbage collected when assigning a null value to the variable :

Object a = new Object;
a = null; //it is now available for garbage collection

or when the object is out of scope due to the method's execution is done:

public void gc(){
    Object a = new Object;
} //once gc method is done the object where a is referring to will be available for garbage collection

given with the out of scope isn't also the same when the application just ended?

class Ink{}
public class Main {
    Ink k = new Ink();

    public void getSomething(){
        //method codes here
    }

    public static void main(String[] args) {
        Main n = new Main();
    }
}

where I expect 2 objects (Ink object and Main object) should be garbage collected when the application ends.

Upvotes: 0

Views: 97

Answers (3)

HamoriZ
HamoriZ

Reputation: 2438

JVM monitors the GC roots - if an object is not available from a GC root, then it is a candidate for garbage collections. GC root can be

  1. local variables
  2. active java threads
  3. static variables
  4. jni references

Upvotes: 0

Holger
Holger

Reputation: 298539

You are confusing the event of an object becoming eligible for garbage collection with the actual process of collecting garbage or, more precisely, reclaiming memory.

The garbage collector doesn’t run just because a reference became null or an object went out of scope, that would be a waste of resources. It usually runs because either, memory is low or CPU resources are unused.

Also, the term “garbage collection” is misleading. The actual task for the JVM is to mark all objects being still alive (also known as reachable objects). Everything else is considered reclaimable, aka garbage. Since at the termination of the JVM, the entire memory is reclaimed per se, there is no need to search for reachable references.

That said, it’s helpful to understand, that most thinking about the memory management is useless. E.g. in your code:

public void gc(){
    Object a = new Object;
    // even here the object might get garbage collected as it is unused in subsequent code
}

the optimizer might remove the entire creation of the object, as it has no observable effect. Then, there will no garbage collection, as the object hasn’t been created in the first place.

See also here.

Upvotes: 1

Paul Bilnoski
Paul Bilnoski

Reputation: 556

When the Java application terminates, the JVM typically also terminates in the scope of the OS, so GC at that point is moot. All resources have returned to the OS after as orderly a shutdown of the JVM as the app defined.

Upvotes: 1

Related Questions