Wednesday, January 6, 2010

Myth busting - String.intern() object allocations are never garbage collected

Java is becoming quite old (version 1.0 came out in 1996 if I'm not mistaken). When something turns old, legends, myths, and other perceived truths are quick to form around it (just imagine an old Gothic mansion with its stack of scare tales).
Most of the accumulated knowledge is beneficial and helpful, but some of it is not relevant anymore or just plain wrong.
Remembering that Java is 14 yeas old (2010), when I google for something, for Java info/answers, I always inspect the date of the article I landed on.
If you stumble upon somebody claiming that java can/can't do something, always check his comment's date. If I see something from 2001, you better search for newer references, instead of accepting it as is.

oldSome sites like http://Javaworld.com, have been there from the get go, were big then, but after losing popularity, are now a grave yard for old Java skeletons (I myself have a not that relevant article there).

The story with String.intern() is the same, you'll find people all around the place, claiming that over using it will finish up the perm area, because the perm area is never garbage collected. As discussed here, that's just not true.

Something I enjoy doing is not taking so called "facts" as granted, and re-validating on my IDE.
Thinking that those intern() allocations will never be GCed, I was planing a presentation on how to use weakHashMap based solution can serve as an alternative cache repository for Strings, wrote a program to demonstrate an OMME caused by intern() only to find out that intern() is not so bad  as I originally thought.
Try stuff yourself. You be surprised...

Other myths I'll should wright about some day are:

  1. Regular expressions in Java are slow - FALSE! I've tested this myself, and after compiling the regex, I was able to run over than 1 million matches per second (small strings of course).

  2. Always use StringBuffer to concatenate strings - dead wrong! if you have all concatenations in a single line, like the following, the compiler auto does it for you:
    s= "Hi my name is: "+myName+ ". my lucky number is: "+num;
    Run Javap on a class file using and not using StringBuffer to see that the byte code is the same.
    Though this piece of code could benefit from StringBuffer to prevent rapid object creation:
    for (...) {
    s += strOfThisCycle;
    }
    In any case, Java5 introduces StringBuilder which is the unsynchronized tween of the synchronized StringBuffer class. I guess you will rarely access the same builder from different threads, therefore StringBuilder should be the default choice for ya.

Monday, January 4, 2010

New Java blog out there

A new baby blog was born: Java Tech Sharing.
Proud father: Guy Moshkovich.

I recommend adding to your RSS/Atom reader.