Underneath, AtomicInteger and AtomicIntegerArray typically use the same low level APIs to perform reads, writes and other CAS operations. (For example, OpenSDK 7 uses sun.misc.Unsafe
to perform the CAS operations in both classes.) So there is little performance benefit in using AtomicInteger[]. As you've already noted, the use of AtomicIntegerArray does have significant memory advantages.
On a practical note, the use of the later frees you from having to construct all your AtomicInteger instances, too. Remember that you cannot naively allocate those lazily due to concurrency reasons; you will have to pre-allocate or use some safe publishing mechanism. So in addition to memory advantages, your code is cleaner.
On a similar vein, if you have a bunch of objects with AtomicInteger members, for example:
class ReadCounter {
private final String _fileName;
private final AtomicInteger _readCount;
...
}
private final Map<String, ReadCounter> _counterByName = ...;
Then you can achieve similar memory improvements by modeling the member variable _readCount
as a volatile int
and using AtomicIntegerFieldUpdater
.