[concurrency-interest] On A Formal Definition of 'Data-Race'

thurstonn thurston at nomagicsoftware.com
Tue Apr 16 21:51:59 EDT 2013

Vitaly Davidovich wrote
> The code works as-is.  

Absolutely.  volatile is not needed for correctness

Vitaly Davidovich wrote
> Why?

Well, for performance reasons given the 'undefined/indefinite' visibility of
#hash to other threads.
At least according to the JMM (which has nothing to say about CPU cache
coherency), it is *possible* that each distinct thread that invoked
#hashCode() *could* result in a recalculation of the hash.
Imagine a long-lived Map<String, ?>; and many threads accessing the map's
keyset and for some unknown reason invoking #hashCode() on each key.
If #hash was declared volatile, although there is no guarantee that #hash
would only be calculated once, it is guaranteed that once a write to main
memory was completed, every *subsequent* (here meaning after the write to
main memory) read no matter from which thread would see #hash != 0 and
therefore skip the calculation.

Vitaly Davidovich wrote
> String is too high profile (especially
> hashing it) to do the "naive" thing.

Nothing wrong with being naive; naive can be charming.  

Vitaly Davidovich wrote
> Also, some architectures pay a
> penalty for volatile loads and you'd incur that each time.

Fair point; the JDK authors only get one shot and they can't assume that
volatile reads are cheap

View this message in context: http://jsr166-concurrency.10961.n7.nabble.com/On-A-Formal-Definition-of-Data-Race-tp9408p9466.html
Sent from the JSR166 Concurrency mailing list archive at Nabble.com.

More information about the Concurrency-interest mailing list