intern'd字符串如何在不同的线程和classloarders之间表现? [英] How do intern'd strings behave between different threads and classloarders?

查看:126
本文介绍了intern'd字符串如何在不同的线程和classloarders之间表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java的文档中,它表示在下面的例子中,条件为真:

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())
{
 ....
}

我想知道,如果在考虑 a 和<$时仍然如此c $ c> b 是在不同的主题中定义的,甚至是不同的 ClassLoaders

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.

推荐答案

如果在不同的线程上,是的,条件将为真。

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

如果在不同的类加载器上,我不会指望条件为真。 (但是你真的在使用不同的类加载器加载两个 String 副本吗?)文档中说实习生是在 String ,使用自己的缓存。来自 String #intern 文档

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.

字符串池(最初为空)由类 String 私有维护。

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

(我的重点)

所以如果你以某种方式使用不同的类加载器两次加载 String 类(我不知道你会怎么做,但我打赌有一种方法),然后是两个 String 每个类都有自己的缓存 —在理论。但是,实施可能不会那么好。 intern 是Oracle JVM中的本机方法,使用在C ++中实现的符号表。我没有密切关注逻辑,看看在你所说的边缘情况下,同一JVM中的两个 String 实例将共享相同的符号是否表。但在那时,我们正在考虑实施,这可能会有所不同。 文档建议不,它们不是相同的字符串。

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.

这篇关于intern'd字符串如何在不同的线程和classloarders之间表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆