Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe lazy initialization

I've read about thread-safe lazy initialization and I look at the implementation of the hashCode method in the String class. Apparently this method is thread-safe, I made my own version of it for another class (immutable).

private int hashcode;

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

My question is : Is it really thread-safe ? I don't understand why. I do not see what prevents a thread to enter the method while another is still inside, but maybe it got it wrong.


1 Answers

The code you are seeing is just possibly inefficient. What could happen is that multiple threads enter the hashCode() function at the same time and they both compute the hash code instead of just one of them computing the hash code and the others waiting for the result.

Because String is immutable, this is not a problem. If the object was mutable, it would need synchronization in its hashCode() function (because the object's state could be changed whilst inside of hashCode().

like image 132
randers Avatar answered Aug 17 '26 11:08

randers