[concurrency-interest] Stupid Question

Doug Lea dl at cs.oswego.edu
Tue Feb 12 16:21:23 EST 2013

On 02/12/13 15:41, javamann at cox.net wrote:
> Stupid question time. While going through the code for an ArrayBlockQueue I came across numerous instances where the instance 'lock' is copied to a variable in a Method. I know there is a reason for this, I just don't know what it is.

It's ultimately due to the fundamental mismatch between memory models
and OOP :-)

Just about every method in all of j.u.c adopts the policy of
reading fields as locals whenever a value is used more than once.
This way you are sure which value applies when.
This is not often pretty, but is easier to visually verify.

The surprising case is doing this even for "final" fields.
This is because JVMs are not always smart enough to exploit
the fine points of the JMM and not reload read final
values, as they would otherwise need to do across the
volatile accesses entailed in locking. Some JVMs are smarter
than they used to be about this, but still not always
smart enough.


> Thanks
> -Pete
>      public int remainingCapacity() {
>          final ReentrantLock lock = this.lock;
>          lock.lock();
>          try {
>              return items.length - count;
>          } finally {
>              lock.unlock();
>          }
>      }
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

More information about the Concurrency-interest mailing list