[concurrency-interest] ThreadPoolExecutor implement question!

Doug Lea dl at cs.oswego.edu
Thu Sep 21 07:15:01 EDT 2006


Hanson Char wrote:
> Is such optimization only applicable to final fields, but not instance 
> member fields in general ?  Does this mean if a final field is accessed 
> more than once in a method, it's always faster to assign it first to a 
> local variable ?
> 

JVMs are generally smart enough to do this, when they are allowed to.
They are not allowed to, for example if you have
   a = somefield;
   synchronized(this) { b = somefield; ... }
According to the JMM (Java Memory Model), b cannot in general just
use the load from a.

JVMs must completely understand and enforce all the rules of the JMM.
Which they do, but sometimes too conservatively. The performance glitch
here is that JVMs don't always understand that a final field that itself
references a lock doesn't have to be reloaded across its own lock boundary,
when it is again used to perform the corresponding unlock. This
is a fairly subtle fact that escapes the attention of at least
some JVMs.

This is a micro-optimization that matters less as JVMs get smarter,
and even so, is hardly ever worth doing (which is why we don't
talk about it much) unless you are writing library code used
by millions of people where you might as well make it as fast
as you know how.

-Doug


More information about the Concurrency-interest mailing list