[concurrency-interest] Stupid Question

Zhong Yu zhong.j.yu at gmail.com
Tue Feb 12 17:26:52 EST 2013


On Tue, Feb 12, 2013 at 3:21 PM, Doug Lea <dl at cs.oswego.edu> 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.

(Forget reflection/Unsafe, only consider typical JMM actions) Can JVM
always cache the value of a final field? What if `this` was leaked
before constructor exit? And if the 1st read sees a non-null value,
can that value then be cached safely?

Zhong Yu


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