问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/9294134/how-do-internd-strings-behave-between-different-threads-and-classloarders