Reputation: 2408
Is there any difference in meaning of AtomicIntegerArray
and AtomicInteger[]
?
And which one is faster to use?
(only thing that I noticed is that first is taking much less space, but that means that each recheck is checking boundaries of array, so that would make it slower?)
Edit: In a scenario where array is pre-initialized.
Upvotes: 17
Views: 6580
Reputation: 38878
I agree with Tom Hawtin's first paragraph…
AtomicInteger[]
will require an object per element.AtomicIntegerArray
just requires theAtomicIntegerArray
object and an array object. So use the latter if possible.
…but it should also be noted that AtomicInteger[]
is not thread safe. Specifically, the array's references to the individual AtomicInteger
objects may or may not be correct if accessed from multiple threads. Synchronizing access on the array object itself will eliminate this issue, though.
Upvotes: 1
Reputation: 13374
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
.
Upvotes: 2
Reputation: 3545
Upvotes: 7
Reputation: 147164
AtomicInteger[]
will require an object per element. AtomicIntegerArray
just requires the AtomicIntegerArray
object and an array object. So use the latter if possible.
The cost of bounds checking is quite small even for normal arrays. What might be significant is that access to data in the same cache line from multiple processors can cause significant performance issues. Therefore separate objects, or deliberately avoiding close elements of an array, can help.
Upvotes: 12