gpt4 book ai didi

java - 修改后的String.hashCode()的重新排序说明

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:59 25 4
gpt4 key购买 nike

引用这个blog还有这个topic .

似乎即使在单线程中代码也会重新排序?

public int hashCode() {
if (hash == 0) { // (1)
int off = offset;
char val[] = value;
int len = count;

int h = 0;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return hash; // (2)
}

但我真的很困惑,为什么 (2) 可以返回 0 而 (1) 可以不为零?

如果我在单线程中使用代码,这甚至都行不通,怎么会发生呢?

最佳答案

第一点java memory model是:

Each action in a thread happens before every action in that thread that comes later in the program's order.

这就是为什么在单线程中重新排序是不可能的。只要代码不同步,就不会为多线程提供此类保证。

查看 String hashCode 实现。它首先将散列加载到局部变量,然后才执行检查和返回。这就是防止此类重新排序的方式。但这并不能使我们免于多次 hashCode 计算。

关于java - 修改后的String.hashCode()的重新排序说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16812321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com