Quick revision
The short answer
We call tryOptimisticRead() to get a stamp without taking any lock, copy x and y into local variables, and then call validate(stamp). If validate returns true, no writer took the write lock since the stamp was issued, so the two copies are a consistent pair and we use them. If it returns false, or the stamp was 0 because a writer held the lock, we fall back to a real read lock with readLock(), read the fields again and release with unlockRead(stamp) in finally.
What to remember
In this answer, we wrote an optimistic read for a Point: get a stamp with tryOptimisticRead(), copy x and y into locals, call validate(stamp), and only then use the copies, falling back to readLock() and unlockRead() in finally when validation fails. Validation fails when a writer held the lock as the stamp was issued, giving stamp 0, or acquired it at any point since. Because the optimistic path only reads the lock's state, it takes no lock and writes no shared memory, which makes it very cheap when writes are rare.
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.
We call tryOptimisticRead() to get a stamp without taking any lock, copy x and y into local variables, and then call validate(stamp). If validate returns true, no writer took the write lock since the stamp was issued, so the two copies are a consistent pair and we use them. If it returns false, or the stamp was 0 because a writer held the lock, we fall back to a real read lock with readLock(), read the fields again and release with unlockRead(stamp) in finally.
Why this question is asked
StampedLock is the fastest lock in the JDK for read-mostly data with very short reads, because its optimistic read does not write any shared memory at all. The price is a pattern that must be followed exactly, since the code briefly reads data that might be in the middle of a change. Interviewers ask for the Point example because it is the smallest case that shows every rule: copy, validate, then use, with a fallback. In this answer, we will recap what a stamp is, write the full Point class, walk through the optimistic read line by line, look at exactly when it falls back, and see why it is cheap.
1A Quick Recap of StampedLock
StampedLock, added in Java 8, has three modes. Writing is exclusive, like a write lock. Reading is shared, like a read lock. And optimistic reading is not a lock at all: it is a promise to check afterwards whether a writer interfered. Every acquisition returns a stamp, a long number that represents the lock's version at that moment. We pass the stamp back when we unlock or validate. A stamp of 0 means the attempt failed.
Internally, every write lock acquisition changes the version. So if the version is the same before and after our reads, no write lock was acquired in between, and what we read is consistent.
2The Full Point Class
Here is a Point whose coordinates move together, with a write method and an optimistic read of the distance from the origin.
Notice that the write side looks like any other lock, except that we keep the stamp from writeLock() and give it back to unlockWrite(). The interesting part is the read.
3Walking Through the Optimistic Read
First, tryOptimisticRead() returns a stamp that records the current version, or 0 if a writer holds the lock right now. It does not block and does not write anything.
Second, we copy x and y into local variables. This step matters. A writer may be changing the fields while we read them, so cx and cy might be a mismatched pair, for example the new x with the old y. That is fine for now, because we have not used them yet. What we must not do is read the fields again later, since then we would be using values that validate() never covered.
Third, validate(stamp) checks that no write lock was acquired since the stamp was issued. It also includes a memory fence, so the reads before it cannot be moved after it by the compiler or processor. If it returns true, the copies form a consistent snapshot, the same as if we had read them under a lock.
Fourth, and only then, we compute with the copies. The rule is: copy, validate, then act. Any decision taken before validate returns true could be based on inconsistent data.
- tryOptimisticRead()returns a stamp, or 0 if a writer holds the lock
- Copy x and y into localsno decisions yet; values may be inconsistent
- validate(stamp)?YesUse the copies, doneNoFall back
- readLock()shared lock, waits for any writer
- Read x and y again, unlockRead in finally
- Compute with the copies
6 steps in order. Play them, or step through them one at a time.
The fast path writes no shared memory; the fallback behaves like a read lock.
4When the Optimistic Path Falls Back
validate(stamp) returns false in two cases. If a writer held the lock when we called tryOptimisticRead(), the stamp was 0, and validate(0) is always false. And if a writer acquired the write lock at any time after the stamp was issued, even if it has already finished, the version changed and validation fails.
Notice what does not cause a fallback: other readers. Optimistic readers and even threads holding the full read lock do not change the version, so any number of them can run at once without disturbing each other. That is why the optimistic path is so effective when writes are rare.
In the fallback we take readLock(), which blocks while a writer holds the lock and then gives us a shared read lock. Under it, the fields cannot change, so we read them again and release in finally. Some code retries the optimistic read once or twice before falling back; that is fine, but the fallback must exist, otherwise heavy write traffic could make a reader spin for a long time.
5Why the Optimistic Read Is Cheap
A normal read lock, in ReentrantReadWriteLock or StampedLock's own readLock(), writes to shared memory: it increments a reader count with an atomic operation, and that cache line bounces between cores when many readers are active. An optimistic read only reads the lock's state twice, once in tryOptimisticRead() and once in validate(). Reads of a cache line can be shared by all cores at the same time, so readers scale with the number of cores instead of fighting over one counter.
The trade-off is that the optimistic path assumes conflicts are rare. When writes are frequent, many reads fail validation and pay for the optimistic attempt plus the real read lock, and the gain disappears. So StampedLock fits data such as coordinates, prices or small configuration values that are read constantly and written occasionally.
6Follow-up questions
Why must the fields be copied into locals before validating?
Because validation only covers the reads made before it. If we validated and then read x and y again, a writer could change them between the validation and the second read, and we would use values the stamp never protected. Copying first means the values we use are exactly the ones validated.
Can code inside the optimistic section throw because of inconsistent values?
Yes, if it is careless. With references, a field could be null or point to an object whose state is mid-change, and calling a method on it could throw or loop. That is why the optimistic section should only copy plain values and do nothing that depends on them until validate returns true.
Does StampedLock support upgrading from read to write?
It offers tryConvertToWriteLock(stamp), which returns a write stamp if the conversion is possible, for example when the caller is the only reader, and 0 otherwise. The caller must check for 0 and then release and acquire the write lock normally.
7Conclusion
In this answer, we wrote an optimistic read for a Point: get a stamp with tryOptimisticRead(), copy x and y into locals, call validate(stamp), and only then use the copies, falling back to readLock() and unlockRead() in finally when validation fails. Validation fails when a writer held the lock as the stamp was issued, giving stamp 0, or acquired it at any point since. Because the optimistic path only reads the lock's state, it takes no lock and writes no shared memory, which makes it very cheap when writes are rare.
Open with
I would write it as: long stamp = sl.tryOptimisticRead(); then copy both fields into locals, double cx = x, cy = y; then if (!sl.validate(stamp)), fall back: stamp = sl.readLock(), read x and y again into the locals inside a try, and call sl.unlockRead(stamp) in finally.
Then, if they want more
Only after that do I compute, for example the square root of cx squared plus cy squared. The write side is a normal exclusive lock: long stamp = sl.writeLock(), update both fields, unlockWrite(stamp) in finally. The important rule is copy, validate, then act.
During the optimistic read a writer may be changing the fields, so the copies may be inconsistent, but that is harmless as long as I do not use them or throw because of them before validate returns true. validate also has a fence, so the reads cannot move after it.
The fallback happens in two cases: when a writer held the lock as I called tryOptimisticRead, so the stamp is 0 and validate is always false, and when a writer acquired the write lock at any time after the stamp was issued. Other readers never cause a fallback.
The optimistic path is cheap because it takes no lock and writes no shared memory, it just reads the lock's version twice, so it scales across cores when writes are rare. If writes are frequent, many validations fail and it loses its advantage.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- 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
- java.util.concurrent, package 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 "Write an optimistic read using StampedLock for a Point with fields x and y, and explain...": https://scrivio-interview-library.netlify.app/java/locks/af76bbb093/