[concurrency-interest] Converting the AtomicXXXArray inner elements to an array

Doug Lea dl@cs.oswego.edu
Mon, 26 Jan 2004 20:47:31 -0500


> We have recently added contructors to the AtomicXXXArray classes for
> both convenience and speed. At this time, if you want to take a
> snapshot (>> understand a copy<<) of the AtomicXXXArray inner values
> for any purpose, you have no other choice than to get every element
> individually. This is OK but is it efficient (or elegant) ? Specially
> if you do it often, accessing to the array 'elements' through a method
> is more CPU intensive than doing a regular array access.

I don't believe there is any advantage to doing this internally,
because the retrievals still have to obey volatile access semantics.
And JVMs are pretty good at eliminating the call overhead.
(Initialization was a different story, because there is an internal
barrier optimization that can be applied there, but nowhere else.)

There is still the argument of convenience though. My hesitation about
this the first time it was raised is that it is too easy to think that
a toArray method maintains atomicity (i.e., provides a snapshot of one
instant of time) when it cannot. And to mistakenly rely on this even
if you know it cannot.  Speaking for myself, I'd rather be reminded
about this by being forced to write a loop to avoid this sort of
subtle thinking error.  People who are less prone to making this kind
of mistake can always make a subclass with toArray.

-Doug