final vs. volatile instance fields

Aleksey Shipilev aleksey.shipilev at
Wed Dec 26 04:31:57 PST 2012

Hi Peter,

You should really consider reading JSR 133 Cookbook:

I think you will need to move this discussion on concurrency-interest@ if you want the discussion on broader cross-hardware cross-implementation scope.

On 26.12.2012, at 15:58, Peter Levart <peter.levart at> wrote:

> Are there any performance differences in reading and writing of volatile vs. final instance fields? I can see that reflection is doing the same for both types (via UnsafeQualifiedFieldAccessorImpl subtypes) and is reading/writing the fields using Unsafe.getXxxVolatile/putXxxVolatile. So what does the JIT compiled code do?

The short answer is that volatile read generally entails more than just a read, it should also conform to JMM, and as such entail barriers, which might exhibit performance costs due to breaking the pipelining, register allocation, ant other fruitful optimizations. While the barriers might be no-oped on some hardware (x86 included), the compiler effects are still in place.

Writing final fields is troublesome to reason, and I fully expect JVMs to bailout to volatile-like semantics to preserve (weaker) final fields invariants.

> a) Are there any differences between writing to those two types of fields? The Java spec. mandates writing to final fields exactly once in the constructors and Java Memory Model says that they are "frozen" at the end of constructor. What does "freeze" actually translate to in the compiled code?

Final fields entail the barrier at the end of constructor, and then piggyback heavily on data-dependency (absence) of reordering. Cookbook explains this well enough. And writing volatile fields can incur prohibitive costs due to JMM effects needing to be enforced.

> b) I can understand that the JIT compiler can generate code that caches the value of final field say in a register, but initially the code has to load the value from a final field and the question is whether this initial load is any different from a volatile read?

Uhm... Depends on "difference". Yes, reading the final field requires reading the object reference first, and so we can piggyback for almost all of the commodity hardware to not to reorder dependent reads. On hypothetical hardware (Alpha, die already!) you have no such guarantee and reading the final fields will incur barriers similar to volatile read.

-------------- next part --------------
An HTML attachment was scrubbed...

More information about the hotspot-runtime-dev mailing list