Sunday, June 22, 2008

The leak continues..

This again is a follow up of my previous post - The Interesting Leak.
I was quite amused after reading Markus' follow-up post An interesting leak when using WeakHashMaps.
What surprised me most was If you put
("abc" + "def").intern();
as key in the WeakHashMap, it doesn't get GC'd whereas
(new String("abc") + "def").intern()
as key leads to the entry being garbage collected.
Tried all combinations. No clarity. Last resort - Pinged Rajiv.
And so went the conversation -

Me : If you put ("abc" + "def").intern(); as key, it doesnt get GC'd but if you put (new String("abc") + "def").intern() it gets GC'd
Rajiv : Decompile and see if "abc"+"def" is being converted to "abcdef" by javac
Me: Yes it is. So?
[This could be the clue. Am still thinking.. tick tick tick]

Rajiv: Check if "abcdef"== (new String("abc") + "def").intern()
Me: It is... printed the identitity hashcodes.
Rajiv: In the class you have both "abcdef" and (new String("abc") + "def").intern() and still
(new String("abc") + "def").intern() gets gc'ed?
Me: God! Then it doesn't get gc'd.
[Now Rajiv cracks it -]

Rajiv: "I think intern is weak map and constant pool has a strong ref"
Me: ohh!
Me: In that case (new String("abc") ).intern(); should get GC'd right? But we saw it doesn't. The maya happens only when someString is '+'d to (new String("abc")) and then the resultant String is interned.
Me: Just (new String("abc")).intern() doesnt get GC'd.
Rajiv: When you say (new String("abc")).intern() there is a string "abc" in constant pool.
Me: Yes "abc" in constant pool would be the literal we created and passed as argument to the String constructor.
Rajiv: (new String("abc")).intern() returns that string. So wont get gc'ed
Me: Oh yeah. Got it!
Me: So only when you do a "+" you get a String which is not there in constant pool and hence it gets GC'd ...
Rajiv: ya right.

I had earlier thought of intern pool and constant pool to be the same. But Rajiv 's prediction of intern being a weak map and constant pool holding a strong ref looks quite convincing.
Oo la.. That solved our mystery. Thanks Rajiv:-)


Joshua Smith said...

The survey is amazing. Thank you for news. To protect yourself from unexpected losses try compare homeowners insurance rates by state to save more on home insurance policies.

trinithis said...

I'm not going to dig up it, but I suspect that ("x"+"y") is optmized to an "xy" string literal. I have no idea if the Java language mandates it, if it is an arbitrary optmization, or if this is even the source of the problem.

Alex daina said...

Vehicle title advances are not for everybody. They work for those shoppers who are in the situation to pay back what they obtained when expected yet for the individuals who can't?