[concurrency-interest] Clarification: volatile, final and atomic ops
dcholmes at optusnet.com.au
Thu Jan 15 19:45:25 EST 2009
Jason T. Greene writes:
> Ashwin Jayaprakash wrote:
> > Thanks Jason!
> > I knew about JSR-133, but it still does not clarify if accessing a
> > "final" field or local variable is slower than a non-final field, for
> > what ever reasons... Does a final field/variable access incur
> > additional cost?
> A final field has cost since it does prevent certain reorderings that
> allow it to be safely published to another thread. Although, due to it's
> restrictions, final field access can be optimized more than
> volatile access.
But note that, sadly, compilers have not, in the past, been good at doing
this. Hence you will often see in code that a final field is loaded into a
local variable if used a number of times.
And a "final local variable" has no runtime semantics and no associated
costs - it is completely unrelated to use of final/volatile in the memory
model. final local variables and final method parameters are a compile-time
indicator that a variable will not be assigned to, which is needed if the
variable is to be accessed from an inner class.
More information about the Concurrency-interest