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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With