Click here to Skip to main content
16,020,377 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i learned in Java that if an object doesn't have any reference to it, it will be garbage collected automatically, but why the object below works fine and doesn't have any reference to it, shouldn't it be garbage collected?
Java
public class Main {

    public static void main(String[] args) {
	new A().show();
    }
}


class A{
    void show(){
        System.out.println("Java");
    }
}


What I have tried:

there was nothing i could try!
Posted
Updated 25-Apr-19 5:22am
Comments
[no name] 25-Apr-19 11:11am    
Your comments bear no relation to what you're showing. You're showing an apple while commenting about the taste of oranges.
hiwa doski 25-Apr-19 12:30pm    
if garbage collector is not related to this then i don't know what is ?
Richard MacCutchan 25-Apr-19 12:36pm    
Look at your code. You create a new object of the A class and call its Show method. You then terminate your application. So how do you know the garbage collector was never called?
hiwa doski 25-Apr-19 12:49pm    
i thought the garbage collector will immediately start and remove it, but it turned out that I was wrong.
Richard MacCutchan 25-Apr-19 12:56pm    
I ask again: how do you know that it didn't?

1 solution

Why would a garbage collector be called in when your app exits? It's a load easier to just release all memory as a lump without worrying about disposing of each individual object - the app is dying, so just release all allocated memory back to the system instead.

And do remember that the garbage collector doesn't fire up immediately anything goes out of scope - it will wait until it's actually needed or the system is idle before it starts checking to see if anything is releasable. In your example the system is never idle until the app exits, and by that stage, it's too late for the GC to start work!
 
Share this answer
 
Comments
hiwa doski 25-Apr-19 11:29am    
what you mean by "when your app exits"
Richard Deeming 25-Apr-19 11:37am    
When the main method ends, your application exits.
OriginalGriff 25-Apr-19 11:45am    
Hard to believe anyone could get this far without realising that, isn't it?
Richard Deeming 25-Apr-19 11:45am    
You must be new here! :D
OriginalGriff 25-Apr-19 12:05pm    
Johnny-come-lately, that's me! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900