I am very curious about that. If you use AtomicIntegerArray with values 0 and 1 you can accomplish the same thing of an AtomicBoolean array. Example:
final Atomi
I'd say that both are equally performant, except when heavily contended. That (as Gray's benchmark show), the AtomicBoolean[]
wins over AtomicIntegerArray
easily. What's missing is the explanation:
While AtomicIntegerArray
places all int
s next to each other as it operates on its internal int[]
, while AtomicBoolean[]
is an array of int
containing objects. These objects add an overhead of few (8 or 12) bytes, so that the underlying int
s are not tightly packed.
So they span a different number of cache lines and here False sharing comes into play. As the cache line is typically 64 bytes, the whole data of new AtomicIntegerArray(10)
fits into it (unless it starts unaligned and then two cache lines get used). This means a 100% probability of false sharing, i.e., it's like all threads contented for a single variable.
With the overhead of AtomicBoolean[]
, we get something like 160 bytes instead of 40 and therefore much less false sharing.
I guess that Gray's benchmark has quite some overhead (%
operations and conditions) and that the real speed difference would be bigger.
This doesn't mean that AtomicIntegerArray
is bad. It's just that it shouldn't be used like this if really heavily contended. The simple solution would be to allocate a much larger array and use only every 16th element, effectively reducing false sharing to zero.