To my understanding, the AtomicReferenceArray class allows the individual elements to be updated atomically. This would make the collection thread-safe. Concurrent collections employ various algorithms to allow the collection to be thread-safe, but also non-blocking. I understand that some of the collection classes provide convenient methods, like add(...)
, or certain functionality like queuing. But ignoring that, and focusing solely on adding and retrieving elements, is there a reason to use one of the concurrent collections rather than an AtomicReferenceArray?
Also, what about performance?
is there a reason to use one of the concurrent collections rather than an AtomicReferenceArray?
Yes, if you need a dynamically sized collection. The AtomicReferenceArray
allows you to atomically get and set elements in the array but you cannot grow the size of the array.
Two threads can reliably change the same element in an AtomicReferenceArray
with compareAndSet(...)
and other methods, but they can't just add data to the array like you can a collection. Using an AtomicReferenceArray
is useful if, for example, each thread has a unique ID and they are updating their personal value in the array. But this would not work if you have two producers who want to add a job to a work list.
Lastly, the complexity of the AtomicReferenceArray
is much less than a true concurrent collection. Concurrent collections allow iterators, deletes, adds, etc. to happen concurrently, safely. The AtomicReferenceArray
class allows test and set spin loops and other functionality but is not a good replacement for a full blown collection.