Can we avoid interning of strings in java?
Asked Answered
I

4

3

Can we completely disable interning of strings. It might not be really helpful, but just a thought. I can think atleast one point where it could be helpful i.e. during jvm tuning, controlling the size of the perm gen.

For e.g. if I give out an OSGI framework and anyone can add any number of bundles of their own and each bundles string interning can completely screw up my tuning parameters. (Ofcourse I know that we should do tuning on a given fixed distro, but still...)

Any thoughts!!

Interval answered 15/4, 2011 at 5:24 Comment(0)
S
6

Permgen size/usage isn't an issue with modern JVMs. Interned strings are made available to the garbage collector when there are no remaining references to them.

(And no, you can't "turn off" interning of string literals).

Swedish answered 15/4, 2011 at 5:28 Comment(3)
all true, but classes would need to be unloaded/gc'ed in order for interned strings to be available for gc.Husbandry
How odd, considering I watch it happen all the time without anything being unloaded. Your statement is incorrect. #1091545 The code in that answer will show you that indeed interned strings are GC'd in modern JVMsSwedish
ah yes if you explicitly intern strings. yes i agree. I was talking about standard constants that are interned by the jvm.Husbandry
F
1

You can disable the interning of most string, by not using any String literals in your code. You could use char[] instead and build Strings from those. E.g.

String hi = new String(new char[] { 'h', 'i' }); // not interned.

As you mentioned, this just creates work for yourself and will just make things worse.

if I give out an OSGI framework and anyone can add any number of bundles of their own and each bundles string interning can completely screw up my tuning parameters

If they add bundles, they could need a higher, maximum memory, perm gen size, direct memory size, different NewSize ratio, even a different GC. The only way to prevent this, is to prevent any other modules in your OSGi container.

Or you can just say, if you add bundles you may need to change the tuning paramters.

Fluellen answered 15/4, 2011 at 7:3 Comment(1)
I was looking some form of jvm parameter that would disable interning. As said before this is only for experimenting purposes. ThanksInterval
D
1

Since Oracle's Java 7 the intern string pool isn't stored in PerGen anymore. Read more here http://java-performance.info/string-intern-in-java-6-7-8/

Demurrer answered 13/12, 2013 at 19:57 Comment(0)
M
-1

String is a final class, and cannot be extended. Therefore, no - you cannot remove the ability to intern Strings in Java.

Massacre answered 15/4, 2011 at 5:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.