views:

52

answers:

3

I want to see example, when would it be good idea to use AtomicReferenceArray.

+1  A: 

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.

irreputable
not exactly correct - see fahd's answer for a description.
aperkins
A: 

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).

starblue
+1  A: 

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.

dogbane
multiple threads can update AtomicReferenceArray elements simultaneously.
irreputable
They can't. Read the link I posted.
dogbane
-1 They can, in the Sun implementation. Otherwise the whole thing doesn't make sense.
starblue
Then what is the difference between `AtomicReferenceArray` and `AtomicReference[]`? Sun's implementation is by Doug Lea.
dogbane
It uses less space, because each atomic reference in the `AtomicReferenceArray` only takes up one pointer. The `compareAndSet` operation is done in `Unsafe` by some special native operation on the pointer.
starblue