Friday, December 3, 2010

Few Basic Things about String intern( ) in Java

Consider a scenario when we read a csv file with very large number of records, we may end up a a lot of duplicate String objects. To avoid duplicate String objects getting created in these kind of scenarios we can use String.intern( ) method.

How it works ? Internally there will be Map/Table of String literals. First time when intern( ) is called on a String, it is added to this table. Subsequent calls String.intern ( ) will return reference to the String in the previous mentioned Table/Map.

Other benefit of interning is that == comparison is much faster.

Say you interned few Strings which got added in the previous mentioned table. How do you remove any of those from the table ? Oops ! Are we Struck here until the program ends ?
In the most recent JVMs, interned Strings are implemented as Soft references, so that they can be garbage collected soon.

Last few points:
  • String literals at compile time will be automatically interned, But literals created on run time(like command line arguments) will not be interned.

1 comment:

  1. Lot of abstract internal details in Java (JVM)!! Sting is really special and handled very nicely based on scenario. It's informative.

    ReplyDelete