wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage collector Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage collector " Watch "Garbage collector " New topic
Author

Garbage collector

ms
Greenhorn

Joined: Oct 18, 2000
Posts: 10
Hi all ,
Can somebody tell me the correct answer and explain why is that so ?
Which is the earliest line in the following code after which the object created on the line marked (0) will be a candidate for being garbage collected, assuming no compiler optimizations are done?
public class Q76a9 {
static String f() {
String a = "hello";
String b = "bye"; // (0)
String c = b + "!"; // (1)
String d = b;
b = a; // (2)
d = a; // (3)
return c; // (4)
}
public static void main(String args[]) {
String msg = f();
System.out.println(msg); // (5)
}
}
Lam Thai
Ranch Hand

Joined: Apr 02, 2001
Posts: 117
Originally posted by ms:
Hi all ,
Can somebody tell me the correct answer and explain why is that so ?
Which is the earliest line in the following code after which the object created on the line marked (0) will be a candidate for being garbage collected, assuming no compiler optimizations are done?
public class Q76a9 {
static String f() {
String a = "hello";
String b = "bye"; // (0)
String c = b + "!"; // (1)
String d = b;
b = a; // (2)
d = a; // (3)
return c; // (4)
}
public static void main(String args[]) {
String msg = f();
System.out.println(msg); // (5)
}
}

Let's go through this together:
First b = "bye"
Then d = b, so d now points to "bye" too
Then b = a, so now d is the only address points to "bye" using the same old b's object reference.
Then d = a, so now d no longer points to "bye" using old b's instance... I guess right after this GC can do its clean up as soon as it is ready. So I would say line 4 is the earliest line.
Regards,
Lam

[This message has been edited by Lam Thai (edited April 20, 2001).]
Tanveer Mehmood
Ranch Hand

Joined: Feb 23, 2001
Posts: 51
Hi Lam,
What about the Line 1 where C is created using b. Will it create a new string or otherwise. I think C should also be pointing "bye". Correct me if wrong.
Tanveer
Lam Thai
Ranch Hand

Joined: Apr 02, 2001
Posts: 117
Originally posted by Tanveer Mehmood:
Hi Lam,
What about the Line 1 where C is created using b. Will it create a new string or otherwise. I think C should also be pointing "bye". Correct me if wrong.
Tanveer

Hi Tanveer,
Let's take a look at that line
c = b + "!";
The will create an object reference or an address if you will that points to a different memory block, which contains different character sequence "bye!" - not "bye"
As long as c keeps looking at "bye", it is not ready for GC to reclaim the memory.
Regards,
Lam

[This message has been edited by Lam Thai (edited April 20, 2001).]
nachiket deshpande
Ranch Hand

Joined: Oct 06, 2000
Posts: 114
Hi Lam
I may be wrong but please explain to me,
when we say
String d=b;
does'nt it mean that reference of b object is assigned to d,and so now the b object does'nt have a refence.
also when b=a;//2
can we say reference 'a' is now reference 'b'?
please help..
ratul banji
Ranch Hand

Joined: Mar 15, 2001
Posts: 108
Hi Lam,
I fully agree with u and ur explanation.
But..why u r calling it line 4 ....is it line 4 or line 3.
!!!

Lam Thai
Ranch Hand

Joined: Apr 02, 2001
Posts: 117
Originally posted by nachiket deshpande:
Hi Lam
I may be wrong but please explain to me,
when we say
String d=b;
does'nt it mean that reference of b object is assigned to d,and so now the b object does'nt have a refence.
also when b=a;//2
can we say reference 'a' is now reference 'b'?
please help..

Hi Nachiket,
d = b is just a reference copy op.
Think of what you have just said "does'nt it mean that reference of b object is assigned to d,and so now the b object does'nt have a refence."
If b does not have a reference as you said then what will happen if one assign b to another sring?
We can keep doing this d= b; e =b, x = b... b still points to its content. The reference to the memory block is still there, right? What do you think?
Regards,
Lam
Lam Thai
Ranch Hand

Joined: Apr 02, 2001
Posts: 117
Originally posted by ratul banji:
Hi Lam,
I fully agree with u and ur explanation.
But..why u r calling it line 4 ....is it line 4 or line 3.
!!!

You got me! That would depend on what the question mean by "the earliest line". Is this the head of the line or the tail of the line?
All my answer says is this, as soon as the memory block has no more reference to it, it is ready for GC. In order to do that, I think the expression b = a has to be completed first and then GC will come into the picture. May we say the first instruction after line //3 or at the end of line //3 or is it at the beginning of line //4 - take your pick and have fun :-)
I wish human language can be as precise as that of the computer!!!
Regards,
Lam


[This message has been edited by Lam Thai (edited April 20, 2001).]
Cameron Park
Ranch Hand

Joined: Apr 06, 2001
Posts: 371
What about String literal pool? When you create a String object like new String("line"); It is an object that can be garbage collected. But when you say b="line"; "line" is kept in the literal pool and will not be garbage collected.
Lam Thai
Ranch Hand

Joined: Apr 02, 2001
Posts: 117
Originally posted by Cameron Park:
What about String literal pool? When you create a String object like new String("line"); It is an object that can be garbage collected. But when you say b="line"; "line" is kept in the literal pool and will not be garbage collected.

Hello Cameron,
Maybe I mislead you. But that was not the intention. "line" is not what is ready for GC, the old string instance b is!
I once thought the same as you did. And I was told that the process of constant pool resolution for string will create a new instance of class String containing the sequence of Unicode represented by the CONSTANT_String entry; that class instance is the result of resolution (per Java Virtual Machine Specification). What this says is that the first time the string is resolved from the constant pool, an instance of the string is created on the Java heap. Any other subsequenct references to the same literal in the constant pool always return the reference of the string instance that was already created.
With that I was told when b is either set to null or is recreated via an assignment such as b = new string, then the old reference object is ready for GC. I did not want to get into this kind of detail but I guess what I said earlier with "bye" and "bye!" was kind of confusing isn't it?
Now let's take a look a this code:
String b = "Hello";
String a = b;
b = "Goodbye";
These three lines of code witll yield false when we later compare a with b. While a has the copy of the reference of the old b instance. The new b has a different one. In this case the old b is ready for garbage collection right after the third line.
But then again who say that what I was told was not itself a mistake. Opinion, anybody?
Take care,
Lam


[This message has been edited by Lam Thai (edited April 20, 2001).]
nachiket deshpande
Ranch Hand

Joined: Oct 06, 2000
Posts: 114
Hi Lam!
again need your advice..
String b="bye";//0
String d=b;//1
b=a;//2
d=a;//3
what i get from the above code is at line 1 when reference b is
assigned to d,object "bye" has no reference.and also as you said at line 3 and 4 it's just referene copying.so does'nt it say that after line 1 executes "bye" is eligible for G.C.
please help.
Lam Thai
Ranch Hand

Joined: Apr 02, 2001
Posts: 117
Originally posted by nachiket deshpande:
Hi Lam!
again need your advice..
String b="bye";//0
String d=b;//1
b=a;//2
d=a;//3
what i get from the above code is at line 1 when reference b is
assigned to d,object "bye" has no reference.and also as you said at line 3 and 4 it's just referene copying.so does'nt it say that after line 1 executes "bye" is eligible for G.C.
please help.

Hi Nachiket,
I am sorry for confusing you and others. I did not intend to say "bye" is to be ready for GC. It is the old object reerence of b. Let's see if I can give it another try again with different approach this time:
First, string b = "bye" can be shown as:
Address in heap-----------------------Address in memory pool
b | XXXX ref | -------> link ----------> "bye"
Second, string d = b can be shown as follows:
Address in heap-----------------------Address in memory pool
b | XXXX ref | -------> link ----------> "bye"
d | XXXX ref |
Third, b = a can be shown as follows:
Address in heap-----------------------Address in memory pool
a | YYYY ref | -------> link ----------> "sun" (is it "sun"?)
b | YYYY ref |
Note that b's object reference now is YYYY, which belongs to a. XXXX ref is still being used by d.
Finally, d = a can be shown as follows:
Address in heap-----------------------Address in memory pool
a | YYYY ref | -------> link ----------> "sun" (is it "sun"?)
d | YYYY ref |
a, b, and d are now all involved with YYYY ref. XXXX ref is now abandoned. Therefore right after d = a or at the beginning of the next line | XXXX ref | is ready for GC.
Hope this helps.
Take care,
Lam
ms
Greenhorn

Joined: Oct 18, 2000
Posts: 10
Thanks a lot Lam for a detailed note .
Want to just check on one issue :
Do u mean to say that when we make a literal in String pool ....a new String instance is created at the heap .Then why does the result for two string literals say s1 and s2 comes out to be true
Example :
String s1 = "Hello" ;
String s2 = "Hello" ;
s1 == s2 ... gives true
Their behaviour should also be like String objects ?

2nd Point :
As per you :
WHen I declare String literal :
String b = "bye" ;
String c = b + "!" ;
It will be resolved as (object pointed by refrence b) + "!"
for once which will evaluate as bye! and assigned to refrence c
at compile time .After this b has no relevance in the c's context .
AmI right in my understanding !
Hope am not that ambiguous !
Lam Thai
Ranch Hand

Joined: Apr 02, 2001
Posts: 117
Originally posted by ms:
Thanks a lot Lam for a detailed note .
Want to just check on one issue :
Do u mean to say that when we make a literal in String pool ....a new String instance is created at the heap .Then why does the result for two string literals say s1 and s2 comes out to be true
Example :
String s1 = "Hello" ;
String s2 = "Hello" ;
s1 == s2 ... gives true
Their behaviour should also be like String objects ?

2nd Point :
As per you :
WHen I declare String literal :
String b = "bye" ;
String c = b + "!" ;
It will be resolved as (object pointed by refrence b) + "!"
for once which will evaluate as bye! and assigned to refrence c
at compile time .After this b has no relevance in the c's context .
AmI right in my understanding !
Hope am not that ambiguous !

Hi,
If you look at my answer, about three threads above this, you would see that the compiler is smart to have both s1, and s2 point to the same constant. What I mean is that the two following snippets will behave the same:
#1 String a = "Hello"; String b = a;
#2. String a = "Hello"; String b = "Hello"
That is the reason why you can compare if (a == b) and get true result in both situations. Note that #2 is a special case that will yield a is equal to b; But if you have
String b = "Hell", String c = "o", and String d = b+c
then you will find out that a is not equal to d because the compiler will allocate different object reference for d. But of course their contents are the same, "Hello."

Regarding your second question of c = b+"!", b still have its reference. Because if you instantiate another String x and let x = b, x will points to "bye". The compiler will allocate another reference for c, that's all!. Remember when you think of GC, look at the object on the LHS of the assignment =expression.
Regards,
Lam

[This message has been edited by Lam Thai (edited April 21, 2001).]
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi all,
Java uses a String pool, a seperate area in memory, to store String literals.
When you write a statement like <code>String s1 = "Hello"</code>, the JVM checks the String pool to see if a String matching "Hello" exists, as there isn't one at this point, the JVM creates a new String object whose contents are "Hello" and places it in the String pool.
When it processes the next statement, <code>String s2 = "Hello"</code>, the JVM again checks the String pool for an object with the same Unicode characters as "Hello". One exists so rather than create a new object, it gets the memory address for the existing "Hello" and returns it to <code>s2</code>.
Only one String object, "Hello", actually exists at this point; however, there are two String references, <code>s1</code> and <code>s2</code> which both contain the same memory address ... the one for the "Hello" object in the String pool.
The next statement, <code>String b = "bye"</code>, goes through the same process. No matching string exists in the pool so the JVM creates a String object with the characters for "bye" and places it in the String pool.
Now we come to <code>String c = b + "!"</code>. This does not create a string literal. The JVM takes the object, "bye", referenced by the String reference <code>b</code>. It then looks at the literal "!". As there is no object in the String pool with matching characters, it creates one. It then concatenates the characters of both objects to form a new String "bye!" which it stores in the heap ... not the String pool.
This leaves us with the following String objects in the String pool:
"Hello" "bye" "!"
And the references <code>s1</code> and <code>s2</code>, both of which hold the memory addresses for the "Hello" object.
Reference <code>b</code> which holds the memory address to the "bye" object; and,
Reference <code>c</code> which holds the memory address to the object "bye!" in Heap memory.
There is no reference to the object "!" which resides in the String pool.
Garbage collection, as specified by the JVM, applies to heap memory. There are no rules about the String pool, a vendor may choose to optimize their JVM platform to gc object in the String pool, but they don't have to. The current version of the JDK does not run garbage collection against the String pool.
So, in these examples, none of the objects are eligible for garbage collection. The three objects in the String pool are ignored and the one object in the heap has a reference.
If <code>c</code> is set to <code>null</code> then the string object "bye!" would become eligible for garbage collection.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
ms,
Please read the JavaRanch Name Policy and re-register using a name that complies with the rules.
Thanks for your cooperation.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
Sri Nivas
Ranch Hand

Joined: Apr 18, 2001
Posts: 58
Jane,
That was a splendid explanation (there were no further questions). I was wondering where to read such info. Is it in the JVM spec in such a detail?
Srini.
nachiket deshpande
Ranch Hand

Joined: Oct 06, 2000
Posts: 114
Hi Jane
your explanation was wonderful!but again clarify about the above ques:String a="hello";//1
String b="bye"//2
String c=b+"bye";//3
String d=b;//4
b=a;//5
d=a//6
What i understand is:two object a and b with contents"hello" and "bye" are in the pool.object c with "bye!" is on the heap.
now at line 4
String d=b--->means d has same contents as b ie"bye".(and "bye"
is in the pool,so no new object is created)
at line 5
b=a---->is reference copying,ie b and a have same references??
so a and b both are pointing to "hello" or "bye"???
again at line 6
d=a---->is again reference copying ie d and a have same memory address so to wht object are they pointing??
please clarify on reference assignment
thanks!
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Srini,
The JVM has information on the Heap and String constant pool:
JVM §3.5.3 Heap

The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated.

JVM §5.1 Runtime Constant Pool

The Java programming language requires that identical string literals (that is, literals that contain the same sequence of characters) must refer to the same instance of class String. In addition, if the method String.intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as a literal. Thus,

must have the value true.

Mostly, I've been poking around in various articles on Sun's site re: garbage collection and in various Java books.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Nachiket,

now at line 4
String d=b--->means d has same contents as b ie"bye".(and "bye"
is in the pool,so no new object is created)

'd' has a reference to String object "bye" which is the same reference 'b' holds
at line 5
b=a---->is reference copying,ie b and a have same references??
so a and b both are pointing to "hello" or "bye"???

'b' now has a reference to the String object "Hello", which is the same as the reference 'a' holds.
again at line 6
d=a---->is again reference copying ie d and a have same memory address so to wht object are they pointing??

'd' now has a reference to the String object "Hello", which is the same reference that 'a' holds.
A reference variable is a special container that holds the memory address of an object; it does not contain the object itself. It may help to think of it as an index card in a library. When you go to the library and want to look for a specific book, the easiest thing is to go the index files, look up the book title or author. The index file will tell you the book is in 'section such and such'; you then physically walk to the correct section and take the book off the shelf.
A reference variable is used in a similar fashion ... it knows where the object is physically located in memory; but it is not the object itself.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
nachiket deshpande
Ranch Hand

Joined: Oct 06, 2000
Posts: 114
Thanks Jane! It's a great help
srinivasrao marri
Ranch Hand

Joined: Feb 13, 2001
Posts: 61
hi,
i hope the below given matter will clarifies u'r doubt
in java a String is an object but not a primitive datatype. if there is an active object means then it should be referred by a variable. when an object is garbage collected is, if an object is not referenced by any variable. with this analysis look at u'r problem which is pasted below.
public class Q76a9 {
static String f() {
String a = "hello";
String b = "bye"; // (0)
String c = b + "!"; // (1)
String d = b;
b = a; // (2)
d = a; // (3)
return c; // (4)
}
public static void main(String args[]) {
String msg = f();
System.out.println(msg); // (5)
}
}
at (0) a String object is created which is referenced by a reference variable 'b'. the statement String d=b; means the variable d is now pointing the String object through b.
at (2) the reference variable b is referencing a string object 'hello' through 'a' reference variable. still the string object 'bye' is pointed out by a reference variable 'd'. at (3) is pointed to a string object 'hello' through 'a' reference variable.
now at (3) the string object 'bye' got the eligibility to get garbage collected, since there is no any active reference pointing to this object.
hope u got the concept. try to read the matter by looking to the code.
thank you.

------------------
ms
Greenhorn

Joined: Oct 18, 2000
Posts: 10
Thanks a lot Jane . I was not aware of the naming policy and I have re registered myself . Here just to maintain the identity I am following the same id .
Just wanted to know that if the object re -refers itself in the finalize method ...Will it ever be garbage collected ?
Thanks in advance again !
shailesh sonavadekar
Ranch Hand

Joined: Oct 12, 2000
Posts: 1874
Mangalam Sudhir , Thanks very much for re-registering. I think now you should be posting with your re-registered id. If not you please do , because "ms" will be disabled. Please do the needful.
Great Explaination , Jane.
Your Friendly Bartender
Shailesh.
Shallu Shankar
Greenhorn

Joined: Apr 20, 2001
Posts: 15
Hi Shailesh ,
I would appreciate if u also help out in resolving the queries apart from doing this good work of alerting people .
Thanks !
Shallu Shankar
Greenhorn

Joined: Apr 20, 2001
Posts: 15
Hi Jane ,
Thanks for the wonderful explanation ..
According to you : None of the objects in the program given below be garbage collected because all the strings are literals .....am I right in my understanding .
public class Q2 {
public static void main (String[] args) {
String s = "Hello World ";
String s1 = "Hello";
s = s1;
s = null;
s1 = null;
System.out.println(s);
}
}
How many objects will be Garbage collected by the time execution completes Line 8?
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Shallu,
Yes, that's right
Please guys, don't get yourself tied up in knots over gc. Most of the mocks assume String literals are gc'd; the gc questions on the real exam are highly unlikely to refer to String literals as they don't test you on knowledge of specific JVM implementations and gc is system dependent.
What's important is to understand the difference between a primitive type variable and a reference type variable; how Java passes parameters to methods and when objects are no longer accessible ie because all references to them have been set to 'null' or because they were local to a method or code block and no reference to them was passed back to the calling method nor were they assigned to a static reference variable.
Hope that helps.

------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
ms ... thanks for re-registering.
Jane
Shallu Shankar
Greenhorn

Joined: Apr 20, 2001
Posts: 15
Thanks again Jane !
shailesh sonavadekar
Ranch Hand

Joined: Oct 12, 2000
Posts: 1874
Shallu Shankar Wrote

Hi Shailesh ,
I would appreciate if u also help out in resolving the queries apart from doing this good work of alerting people .


I will definitely. But , there are many knowledgable people like you around here. more than What I think , what I can offer , others are there. I think my help will not be necessary.
Regarding , Good work of alerting people. If you like it or not , But , that is my job as moderator , first. To maintain the decorum of the forum & see to that people are following certain normal rules that are being formulated for such a great place of knowledge.
I hope this clears your doubt of alterting people.
Your Friendly Bartender
Shailesh.
[This message has been edited by shailesh sonavadekar (edited April 26, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Garbage collector
 
Similar Threads
Mughal rasmussen
Garbage
Strings and GC
que on GC
Garbage collection