[concurrency-interest] Stupid Question

Remi Forax forax at univ-mlv.fr
Tue Feb 12 16:34:06 EST 2013


On 02/12/2013 10:21 PM, Doug Lea wrote:
> 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.

It's not exactly that the VM is not smart enough, it's that the VM may 
not see enough.
In the example, the VM has to be able to inline the whole graph of 
method behind the call lock.lock() to be sure that no method that is 
part of this graph contains code that may change the value of the field 
lock*. If the VM can prove that, the field doesn't need to be re-loaded 
when calling lock.unlock().

>
> -Doug

Rémi
* and yes, final field can be changed.

>
>
>
>> 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
>>
>
> _______________________________________________
> 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