Quick revision
The short answer
String.hashCode() is correct without volatile because the string's characters never change, so every thread computes exactly the same value, the int field is read and written atomically so no thread can see a half-written number, and a thread that sees the default 0 simply computes the hash again. That reasoning depends on immutable inputs, an idempotent computation and a single atomic field; ordinary application code rarely has all three, so copying the trick usually produces real bugs that reviewers cannot spot, and volatile or proper publication is the right default.
What to remember
In this answer, we saw that String.hashCode() races on purpose and is still correct because its input bytes are immutable, the hash computation is idempotent, an int is read and written atomically, a stale 0 only causes a recomputation, and the field is read once into a local. Application code usually lacks one of these properties, for example it caches mutable or multi-field objects, and then the race lets threads see half-built state. Since reviewers cannot reliably verify such reasoning, the default should be volatile, final fields or proper publication.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
String.hashCode() is correct without volatile because the string's characters never change, so every thread computes exactly the same value, the int field is read and written atomically so no thread can see a half-written number, and a thread that sees the default 0 simply computes the hash again. That reasoning depends on immutable inputs, an idempotent computation and a single atomic field; ordinary application code rarely has all three, so copying the trick usually produces real bugs that reviewers cannot spot, and volatile or proper publication is the right default.
Why this question is asked
Every Java developer has heard that data races are bugs, and then someone points at the JDK's own String class, which caches its hash in a plain field and is called from countless threads at once. Interviewers ask about it to see whether we can tell a deliberate, carefully argued race from an accident, and whether we understand why the same argument rarely survives in our own code. In this answer, we will look at how String caches its hash, go through the three facts that make it safe, and then see what breaks when we copy the pattern into mutable or multi-field objects.
1How String Caches Its Hash
A String's hashCode() depends on all its characters, so computing it walks the whole string. Strings are used constantly as HashMap keys, so the JDK caches the result in a field of the String object the first time it is computed. The field is a plain int, not volatile, and there is no lock. The real JDK code also has a second boolean field for the rare string whose hash is genuinely 0, but the simplified logic below shows the idea.
Two threads calling hashCode() on the same new string at the same moment can both see 0, both compute the hash, and both write it. That is a data race in the strict sense: two threads access the same field, at least one writes, and no happens-before orders them. The question is why the race is harmless here.
2Why This Race Is Benign
The first reason is that the inputs are immutable. value is a final field set in the constructor and never changed, and the final field rules of the Java Memory Model guarantee that any thread that has the String reference sees those bytes fully. So every thread that computes the hash computes it from the same data and gets the same number. The computation is idempotent: running it twice gives the same result as running it once.
The second reason is atomicity. The JMM guarantees that reads and writes of an int are atomic, so a thread sees either 0 or the full hash, never half of one number and half of another. That would not be true for a non-volatile long or double, which the specification allows to be written in two 32-bit halves.
The third reason is that 0 is a safe value to see. A thread that reads the stale 0 does not fail; it just does the work again. So the worst case of the race is a little duplicated computation. Notice also the local variable h: the method reads the field once and returns the local. If it read the field twice, a thread could see the computed hash in the check and a stale 0 in the return, because two racy reads of the same field are not ordered.
| Thread reads hash as | What it does | Result returned |
|---|---|---|
| 0 (not yet visible) | Recomputes from the immutable bytes | 99162322 |
| 99162322 | Uses the cached value | 99162322 |
| A mix of two values | Impossible: int reads are atomic | - |
3Copying the Pattern: Where It Breaks
Now suppose we copy the idea into an application class: a lazily computed summary cached in a plain field.
Each of the three facts is now missing. The input list is mutable, so two threads can compute different summaries if the list changes in between. The cached value is an object reference, and Summary has non-final fields, so a thread can see the reference before it sees the fields written by the constructor; it gets an object that looks half-built, with a total of 0. And the method reads summary twice, so even a correct object could be returned as null on the second read. None of this shows up in tests on a developer laptop, and all of it is allowed by the memory model.
4Why Reviewers Should Push Back
The String case is safe because a small group of JDK experts reasoned about every read and write, and the class has not changed in that respect for years. In application code, the reasoning has to be redone by every reviewer for every change, and a small edit, such as adding a second cached field or caching a long, silently breaks it. Reviewers cannot easily verify that kind of argument, and tests almost never catch the failure.
So the rule I would apply is: use volatile for the cached field, or compute the value eagerly in the constructor and store it in a final field, or use a proper lazy holder. A volatile read on x86 costs about the same as a plain read, and on ARM it costs a little more, which is negligible next to computing a summary. A benign race should be accepted only when measurement shows the field is hot enough to matter, and then with a written argument and a jcstress test, the OpenJDK tool that runs concurrent code millions of times to find forbidden outcomes.
This version may still compute the summary twice under a race, which is fine, but every thread now sees a complete, consistent object.
5Follow-up questions
Why does String need a separate flag for strings whose hash is 0?
Because 0 doubles as not computed. A string whose real hash is 0 would be recomputed on every call, which an attacker could exploit with many such keys. Since Java 13, String has a boolean hashIsZero field that records this case, so the hash is computed once even when it is 0. The extra field is also written racily, and the same three facts keep it safe.
Would the String trick be safe for a long hash?
Not without volatile. The JMM allows a non-volatile long or double to be written as two separate 32-bit halves, so another thread could see a torn value that mixes the old and new halves. Most 64-bit JVMs write longs atomically in practice, but the language does not promise it, and code should not depend on it. Declaring the field volatile makes long and double reads and writes atomic.
6Conclusion
In this answer, we saw that String.hashCode() races on purpose and is still correct because its input bytes are immutable, the hash computation is idempotent, an int is read and written atomically, a stale 0 only causes a recomputation, and the field is read once into a local. Application code usually lacks one of these properties, for example it caches mutable or multi-field objects, and then the race lets threads see half-built state. Since reviewers cannot reliably verify such reasoning, the default should be volatile, final fields or proper publication.
Open with
String caches its hash in a plain int field with no volatile and no lock, so two threads can race on it, but the race is benign for three reasons.
Then, if they want more
First, the input is immutable: the bytes are a final field set in the constructor, so every thread computes exactly the same value from the same data, and the computation is idempotent. Second, the field is an int, and the memory model guarantees int reads and writes are atomic, so nobody can see a torn value.
Third, the default 0 just means not computed, so a thread that sees a stale 0 recomputes and gets the right answer; the worst case is duplicated work. The method also reads the field once into a local and returns the local, which avoids two unordered racy reads.
Copying this into application code is dangerous because those conditions usually do not hold. If we cache an object reference whose fields are not final, another thread can see the reference before the fields and get a half-initialised object. If the inputs are mutable, threads can compute different values. If the field is a long, the write can tear.
And a later edit can break the reasoning without anyone noticing, since reviewers cannot easily check it and tests rarely catch it. So my default is a volatile field or eager initialisation into a final field, and I would accept a benign race only where measurement shows it matters, with the argument written down and a jcstress test.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 13
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "String.hashCode() caches its result in a non-volatile field without synchronization, and...": https://scrivio-interview-library.netlify.app/java/java-memory-model/485194a961/