Java 字符串数组-不必要的同步?
我在研究HFT图书馆。我在下面找到了一个classJava 字符串数组-不必要的同步?,java,multithreading,chronicle,Java,Multithreading,Chronicle,我在研究HFT图书馆。我在下面找到了一个classStringInterner public class StringInterner { @NotNull protected final String[] interner; protected final int mask; protected final int shift; protected boolean toggle = false; public StringInterner(in
StringInterner
public class StringInterner {
@NotNull
protected final String[] interner;
protected final int mask;
protected final int shift;
protected boolean toggle = false;
public StringInterner(int capacity) throws IllegalArgumentException {
int n = Maths.nextPower2(capacity, 128);
this.shift = Maths.intLog2((long)n);
this.interner = new String[n];
this.mask = n - 1;
}
@Nullable
public String intern(@Nullable CharSequence cs) {
if (cs == null) {
return null;
} else if (cs.length() > this.interner.length) {
return cs.toString();
} else {
int hash = Maths.hash32(cs);
int h = hash & this.mask;
String s = this.interner[h];
if (StringUtils.isEqual(cs, s)) {
return s;
} else {
int h2 = hash >> this.shift & this.mask;
String s2 = this.interner[h2];
if (StringUtils.isEqual(cs, s2)) {
return s2;
} else {
String s3 = cs.toString();
this.interner[s != null && (s2 == null || !this.toggle()) ? h2 : h] = s3;
return s3;
}
}
我找到了Peter Lawrey的yt视频,他在视频中解释(或者更准确地说,他只是说)这个类是线程安全的,在多线程环境中工作不需要任何额外的同步。视频yt链接:
我的问题是为什么这个类不需要任何同步
顺便说一句,我对
String
在Java5之前不是线程安全的说法感到好奇;我很想看一篇引文。线程安全和保证线程安全并不是一回事。这可能只是规格上的一个变化。。。而且(所有/大多数/典型/任何)字符串实现在Java5之前实际上都是线程安全的。。。我们应该相信不会拼写“保证”这个词的javadoc吗?:-)JSR133改进了内存模型。这也包括在J2SE Tiger中。这就是Java5.0,Alexey Shipilev建议不要使用String.intern(),并在他的字符串问答中从interning的概念转向重复数据消除。实施重复数据消除器很容易。实施一个实习生是非常困难的!关于这个想法的更多信息,请访问