How expensive are volatile reads?
Hello,
I just wonder how expensive volatile reads are, because I've to read an variable which is written once but read by many threads and which can't implemented using ThreadLocal tricks.
I read the java-one paper about Java's memory model and it mentions that volatile reads are "very cheap".
So a volatile-write is a write-back to main-memory, but what happens when accessing a volatile variable (e.g. boolean) that is written once but read many times?
How much overhead will this cause compared to a normal read and will it limit scaliability?
Thank you in advance, lg Clemens
# 1
volatile reads are generally "very cheap". On the main multi-processor platforms (sparc, x86, x64) things are handled by the cache coherency hardware and nothing special has to be done. Apparently things are different on PPC and IA64. And if I get this the right way around, volatiles on single-processor CMT (chip-multi-threading) systems (like Sun's Niagara) are basically free.
Really all you can do is benchmark your application yourself and so how it fares. Presuming you are using volatile for correctness it will be cheaper than any other runtime correctness mechanism eg locking. The other alternative is to try and re-arrange things so that the field can be made final.
Also note that thinking of things in terms of "write-back-to-main-memory" and "read-from-main-memory" is misleading at best. Although the old memory model was phrased that way it was a conceptual model only. In practice on the main platforms volatile semantics are handled by the cache coherency hardware and nothing special has to be done to make things move to/from main memory.