Which is “better”. AtomicIntegerArray (1/0 as true/false) versus AtomicBoolean[]?

后端 未结 3 2430
孤街浪徒
孤街浪徒 2021-02-20 11:08

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         


        
3条回答
  •  失恋的感觉
    2021-02-20 11:27

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

提交回复
热议问题