Java 11中String#hashCode为何使用局部中间变量?是否关联线程同步?
Awesome question! Let’s break down exactly why that local variable h exists, and clear up whether thread synchronization is part of the picture.
First, let’s recap the code we’re looking at:
public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { hash = h = isLatin1() ? StringLatin1.hashCode(value) : StringUTF16.hashCode(value); } return h; }
1. The main goal: Performance optimization
That local variable h is first and foremost a performance tweak, and a smart one at that. Here’s the breakdown:
- Accessing a local variable (which lives in the current thread’s stack frame) is way faster than accessing an instance field (stored in the heap). By reading the
hashinstance field intohonce at the start, we avoid multiple redundant reads of the heap-stored field throughout the method. - Even when we need to compute the hash code, we assign the result to both
hash(updating the instance field) andh(the local variable). This lets us returnhdirectly, skipping another potentially slow read of the instance field.
2. Thread safety: No synchronization, but graceful race condition handling
This code doesn’t involve synchronization at all, and h isn’t here to enforce thread safety. However, it plays a small role in handling race conditions without breaking correctness—thanks to String’s immutability:
- Strings are immutable, meaning the underlying
valuearray (the character data) can never change once the String is created. So even if multiple threads compute the hash code at the same time whenhashis still 0, they’ll all end up with the exact same result. - If two threads enter the
ifblock simultaneously (both seeinghashas 0), both will compute the hash—but since the result is identical, overwritinghashtwice doesn’t cause any bugs. It’s just a tiny bit of redundant work, no harm done. - The local variable
hensures that within a single thread’s execution, we only check the initial state ofhashonce. Withouth, if we checked the instance fieldhashmultiple times (e.g., in theifcondition and then again when returning), there’s a slim chance another thread could updatehashin between—but since the result is the same, this wouldn’t break anything.hjust makes the method’s behavior more consistent per thread.
To sum it up: The local variable h is primarily for performance (faster access to stack-stored variables), and while it doesn’t handle synchronization, it works seamlessly with String’s immutability to avoid correctness issues in multi-threaded scenarios.
内容的提问来源于stack exchange,提问作者gstackoverflow

