线程安全的惰性初始化

Thread-safe lazy initialization

我已经阅读了有关线程安全延迟初始化的内容,并且查看了 String class 中 hashCode 方法的实现。显然这个方法是线程安全的,我为另一个class(不可变)制作了我自己的版本。

private int hashcode;

@Override
public int hashCode() {
    int h = hashcode;
    if (h == 0 && array.length > 0) {
        hashcode = (h = Arrays.hashCode(array));
    }
    return h;
}

我的问题是:它真的是线程安全的吗?我不明白为什么。 我没有看到是什么阻止了一个线程进入该方法,而另一个线程仍在其中,但也许它弄错了。

您看到的代码可能效率低下。可能发生的情况是,多个线程同时进入 hashCode() 函数,它们都计算哈希码,而不是只有一个线程计算哈希码,其他线程等待结果。

因为String是不可变的,所以这不是问题。如果对象是可变的,则需要在其 hashCode() 函数中进行同步(因为对象的状态可以在 hashCode().

内部更改

正如@JB Nizet 指出的那样,主要问题是您可能有一个 non-empty 数组,其散列恰好是 0。您需要能够区分 "Hash is really 0" 和 "Hash is unknown"。您可以为此使用可为空的 Integer

private final AtomicReference<Integer> hashcode = new AtomicReference<>();

@Override
public int hashCode() {
    Integer h = hashcode.get();
    if (h != null) return h;
    int computedHash = Arrays.hashCode(array);
    hashcode.compareAndSet(null, computedHash);
    return computedHash;
}