Quick revision
The short answer
The colleague is right that a torn value is unlikely on 64-bit HotSpot, but the specification does not promise atomicity for a plain long, and the bigger risk is visibility: without volatile, the monitoring thread may keep seeing an old timestamp for a long time. Declaring the field volatile fixes both when we only need the latest write. If several request threads must produce a maximum or a sum, we use AtomicLong.accumulateAndGet or LongAccumulator, and in every case the cost is tiny compared with handling a request.
What to remember
In this answer, we saw that the colleague is right only about tearing on typical 64-bit JVMs, and even that is an implementation detail, not a guarantee. The larger risk is visibility, because a plain field lets the JIT and caches hide new writes from the monitoring thread. volatile fixes both for a latest-value timestamp, AtomicLong.accumulateAndGet or LongAccumulator gives a correct maximum or sum with many writers, and the cost of either is negligible compared with the work a request does.
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.
The colleague is right that a torn value is unlikely on 64-bit HotSpot, but the specification does not promise atomicity for a plain long, and the bigger risk is visibility: without volatile, the monitoring thread may keep seeing an old timestamp for a long time. Declaring the field volatile fixes both when we only need the latest write. If several request threads must produce a maximum or a sum, we use AtomicLong.accumulateAndGet or LongAccumulator, and in every case the cost is tiny compared with handling a request.
Why this question is asked
Metrics and health code is full of plain fields shared between threads, because it seems harmless: it is only monitoring. But a monitoring thread that sees stale data is worse than no monitoring, because it can raise false alarms or hide a real outage. Interviewers use this scenario to see whether we can separate three different concerns, atomicity, visibility and correctness of the combined value, and pick the cheapest tool that solves each. In this answer, we will look at the code and the colleague's claim, go through each risk in turn, and then choose between volatile, AtomicLong and LongAccumulator, with a word on cost.
1The Code and the Colleague's Claim
Here is the kind of class we are talking about. Each request thread records the time it finished, and a monitoring thread checks every few seconds whether the service has gone quiet.
The colleague's argument is that on a 64-bit server a long is written in one instruction, so nothing can go wrong. That is half of one risk, and it misses the other two.
2Risk 1: Tearing Is Unlikely, but Not Guaranteed Away
The Java Language Specification allows a write to a non-volatile long to be split into two 32-bit writes. On 64-bit HotSpot this almost never happens in practice, because the JIT emits one 64-bit store. But the code would still be relying on an implementation detail, not on the language. A different JVM, a 32-bit build or an unusual code path could legally produce a value that is half old and half new, which for a timestamp could be a date decades away.
So the colleague's statement is a fair description of today's typical deployment, and a poor foundation for code that is meant to be correct.
3Risk 2: Visibility Is the Real Problem
Visibility means: when one thread writes a value, when is another thread guaranteed to see it? For a plain field, the answer is never, unless something creates a happens-before relationship between the write and the read, such as a lock, a volatile access or starting a thread.
In practice, the JIT is allowed to treat a plain field as if no other thread changes it. If the monitoring code reads the field inside a loop or an inlined method, the JIT may load it once and keep the value in a register. The processor's caches and store buffers add smaller delays of their own. The result is that the monitoring thread may keep seeing an old timestamp while requests are flowing, and raise a false 'no requests' alert, or, in the opposite case, keep seeing a recent value after traffic has stopped.
This is why visibility, not tearing, is the larger issue. A torn long needs an unusual JVM; a stale read only needs an ordinary optimisation.
4Fix for the Latest Value: volatile
If all we need is the most recent timestamp, last writer wins, then declaring the field volatile solves both problems at once. The JLS guarantees that volatile long reads and writes are atomic, and every volatile read sees the latest volatile write in the order the writes happened.
4 messages in order. Play them, or step through them one at a time.
Fine for an idle alarm; wrong if the value must be the true maximum.
There is one subtle point with many writers. Two threads may read the clock in one order and write the field in the other order, so the stored value can briefly move backwards by a few milliseconds. For an idle check with a 60-second threshold, that does not matter at all, and volatile is the right answer.
5Fix for a Maximum or a Sum: Atomic Classes
If the value must be correct under concurrent updates, for example the true latest timestamp, a maximum latency or a total count, a plain write is not enough even when it is volatile, because each update is a read followed by a write. We need an atomic read-modify-write.
| Need | Use | Why |
|---|---|---|
| latest value, last writer wins | volatile long | atomic and visible, cheapest |
| true maximum, few writers | AtomicLong.accumulateAndGet | CAS loop keeps the max |
| max or sum, many writers | LongAccumulator or LongAdder | per-cell updates, low contention |
| several fields that must agree | a lock or an immutable snapshot | atomic fields cannot group values |
accumulateAndGet retries a compare-and-set until it succeeds, so the stored value is always the maximum seen. LongAccumulator and LongAdder keep several internal cells so that many writers on different cores do not fight over one memory location, which is ideal for metrics: updates on every request, reads every few seconds.
6What It Costs
A volatile write on x86 costs roughly the price of a locked instruction, in the order of tens of nanoseconds, and a volatile read is about as cheap as a plain read. A request that parses JSON, talks to a database and writes a response takes milliseconds, which is tens of thousands of times longer. Even an AtomicLong compare-and-set under moderate contention is noise at that scale.
So there is no performance argument for the plain field. If profiling ever showed contention on one hot counter with thousands of updates per millisecond, LongAdder is the answer, not removing the guarantees.
7Follow-up questions
Would System.nanoTime() be better than currentTimeMillis() here?
For measuring idle time, yes in one way: nanoTime is monotonic and does not jump when the wall clock is adjusted by NTP. But it only makes sense for differences within one JVM, so it is good for idleness checks and latency, while currentTimeMillis is needed if the timestamp is shown to people or compared across machines.
Why not just use synchronized for both methods?
It would be correct, because a lock gives atomicity and visibility. But it makes every request thread queue on one monitor for a trivial write, and it is heavier than needed. volatile or an atomic class gives the same guarantees for a single value without blocking.
Does the monitoring thread's sleep make the value visible?
No. Thread.sleep has no synchronization semantics in the JLS, so it does not create a happens-before edge. In practice a sleep often causes a fresh read, but correct code cannot rely on that.
8Conclusion
In this answer, we saw that the colleague is right only about tearing on typical 64-bit JVMs, and even that is an implementation detail, not a guarantee. The larger risk is visibility, because a plain field lets the JIT and caches hide new writes from the monitoring thread. volatile fixes both for a latest-value timestamp, AtomicLong.accumulateAndGet or LongAccumulator gives a correct maximum or sum with many writers, and the cost of either is negligible compared with the work a request does.
Open with
I would agree that a torn long is unlikely on 64-bit HotSpot, because it writes longs with one instruction, but the Java specification does not guarantee atomicity for a plain long, so we would be relying on the implementation.
Then, if they want more
The bigger risk is visibility. Without volatile there is no happens-before between the request threads' writes and the monitoring thread's reads, so the JIT can keep the old value in a register and the monitor can see a stale timestamp for a long time, which means false idle alarms or missed outages.
If we only need the latest value, I would declare the field volatile: that makes reads and writes atomic and visible. With many writers the value can briefly go backwards by a millisecond or so, which is fine for an idle check.
If we need a true maximum or a sum, I would use AtomicLong with accumulateAndGet and Math::max, or LongAccumulator and LongAdder when there are many writers, because they spread contention over cells.
The cost of a volatile write is tens of nanoseconds, which is nothing compared with a request that takes milliseconds, so there is no reason to keep the plain field.
About this answer
- Last updated
- 12 November 2026
- 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 "A metrics class stores the last request timestamp in a plain long field written by...": https://scrivio-interview-library.netlify.app/java/java-memory-model/e888ff8ffd/