Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java optimize immutable objects?

Java strings are immutable, and instantiating multiple Strings with the same values returns the same object pointer. (Is there a term for this? "pooling" seems to fit, but that already refers to doing caching to save time by doing fewer instantiations.)

Does Java also do this (the thing without a term) with other (user-defined) classes that are immutable? Can Java even detect that a class is immutable, or is this something unique to the string class?

like image 396
Tespa42 Avatar asked Feb 22 '13 09:02

Tespa42


2 Answers

As others here have said this process with Strings is known as interning.

Its worth mentioning that the behaviour of Strings with the same literal values being the same object may or may not be true in Java 7. From 7 onwards:

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

Take a look at Java SE 7 RFE for the full details on this.

With regards to your own immutable objects Java doesnt do anything special with them - it doesnt know that they're immutable. It may inline methods a little more than otherwise if it can detect that its worthwhile/possible, but as far at the compiler and JVM are concerned they're just another object.

like image 145
Sean Landsman Avatar answered Sep 30 '22 20:09

Sean Landsman


Wrt. Strings, the word you're looking for is interning.

Java won't do this for your own immutable objects. It does have cached versions of boxed primitives, though. See this article on wrapper class caching for more info.

like image 39
Brian Agnew Avatar answered Sep 30 '22 18:09

Brian Agnew