As we dont know that when will GC takes place but we do know that automatic garbage collector calls the finalize()method in an object that is eligible for garbage collection before it actually destroys the object,so we can use this utility of finalize() method to show the info. that actually how many objects are eligible for GC.
I have written a program (with help of eg no.9.2 from book by Khalid A Mughal) to demonstrate this fact :
Now ,at first we have created a class a with two static fields idCount , population which will keep track of current no. of objects.
Then we will take two command line parameters as input ,1st will be no. of objects to be created and 2d will be size of each object.
Since we don't know that GC will ever take place so we have taken size of the object which will force JVM to call objects for termination.The first output shows that all the 5 objects were created and were not garbage collected thus they are eligible for GC (printed at line no.37),now after increasing the size and no of objects to 15 we can see that in output 2 that objects 0 and 1 were called for garbage collection to freeup some space in heap.
c:\>java b 5 5000000
0HELLO
1HELLO
2HELLO
3HELLO
4HELLO
5 : Objects alive i.e available for GC
Output2 c:\>java b 10 50000000
0HELLO
1HELLO
2 : Objects alive i.e available for GC
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
1bye
0bye
Here we can see that 2 objects that were eligible for GC have been terminated or garbage collected
Bravo for the link to this thread, RE: Software to display objects eligible for GC.
I compiled and ran your code, and it displays error:
0 : Objects alive i.e available for GC
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at b.main(b.java:29)
Of course, I will trace the code to figure out why this error is happening. Since I am unfamiliar with this concept (i.e. I'm still on chapters 1 and 5 of Sierra/Bates), kindly provide some guidance to understanding this concept.
How is this program supposed to work. I am perplexed
Sandra, I presume you are using Eclipse to run this and somehow the arguments are not getting passed properly.
You may set the arguments in the Run Configuration in Eclipse.
But for SCJP, it is advised not to use any advanced IDE like Eclipse.
Sandra Bachan wrote:Actually, I am unable to grasp your code.
Are we supposed to pass arguments to the execution of the program, i.e.
java b arg1 arg2 arg3
How is this program supposed to work. I am perplexed
actually no!!
run it in your terminal like this
c:\>java b (no of objects to be created i.e here 5) (size of each object)
here i am providing screen shots of outputs