How do intern'd strings behave between different threads and classloarders?
Asked Answered
T

2

0

In java's documentation it says that in the below example, the condition will be true:

String a = new String("ABC");
String b = new String("ABC");

if (a.intern() == b.intern())
{
 ....
}

I wanted to know, if that is still true when considering that a and b are defined in different Threads, or even different ClassLoaders?

This question rose when I needed an ability to synchronize a block that loads a certain configuration based on an entity's name, so I wanted to do something like:

synchronized (entityName.intern())
{
}

I'm not sure this is a good practice, so I'm probably not going to pursue this direction - but the question still interests me.

Thermoelectric answered 15/2, 2012 at 13:15 Comment(0)
A
3

If on different threads, yes, the condition will be true.

If on different class loaders, I wouldn't count on the condition being true. (But are you really loading two copies of String using different class loaders?) The documentation says that intern is implemented within String, using its own cache. From the String#intern documentation:

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

(My emphasis)

So if you somehow loaded the String class twice using different class loaders (I'm not sure how you would do that, but I bet there's a way), then the two String classes would each have its own cache — in theory. However, an implementation might not make that fine a distinction. intern is a native method in the Oracle JVM, using a symbol table implemented in C++. I haven't followed the logic through closely enough to see whether in the edge case you're talking about, the two instances of String in the same JVM would share the same symbol table or not. But at that point, we're looking at implementation, which could vary. The documentation suggests no, they wouldn't be the same string.

Allstar answered 15/2, 2012 at 13:19 Comment(0)
F
0

Yes - interning works across the whole JVM.

I would be very concerned about your execution environment if you were loading multiple versions of java.lang.String via different class loaders... interning would be the least of your worries.

Firing answered 15/2, 2012 at 13:17 Comment(1)
You're sure it's JVM-wide, even if you (somehow) load String twice using two different class loaders?Allstar

© 2022 - 2024 — McMap. All rights reserved.