I want to see example, when would it be good idea to use AtomicReferenceArray.
looks like it's functionally equivalent to AtomicReference[]
, occupying a little less memory though.
So it's useful when you need more than a million atomic references - can't think of any use case.
It could be useful if you have a large number of objects that are updated concurrently, for example in a large multiplayer game.
An update of reference i
would follow the pattern
boolean success = false;
while (!success)
{
E previous = atomicReferenceArray.get(i);
E next = ... // compute updated object
success = atomicReferenceArray.compareAndSet(i, previous, next);
}
Depending on the circumstances this may be faster and/or easier to use than locking (synchronized
).
If you had a shared array of object references, then you would use an AtomicReferenceArray
to ensure that the array couldn't be updated simultaneously by different threads i.e. only one element can be updated at a time.
However, in an AtomicReference[]
(array of AtomicReference
) multiple threads can still update different elements simulateously, because the atomicity is on the elements, not on the array as a whole.
More info here.