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

后端 未结 3 2371
孤街浪徒
孤街浪徒 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:41

    Which one do you think is faster and better?

    Interesting question. The speed of this would probably only be visible if you are doing some very large number of cycles. Otherwise worrying about it smacks as premature optimization. I would pick the pattern that is the cleanest and most easily maintained.

    Under the covers, both methods use the Unsafe.compareAndSwapInt(...) so the performance may be very similar. Since there is no blocking with accessing of volatile storage, this is not about collisions. The AtomicBoolean array will certain have a larger number of objects associated with it – each with their own volatile storage. Also, under the covers the AtomicBoolean stores the boolean value as an int so no savings there.

    My instinct tells me to use the AtomicIntegerArray. Less code for you to write which typically means more reliance on the JDK to do the right thing. To figure it out you would have to test some large number of iterations on your production architecture to know for sure. I suspect the difference is going to be negligible and hard to measure.

    Not a great answer but hopefully something helpful here.

    Edit:

    So I just ran some tests and I can't see any significant differences. Here's my little test program. It used 100 threads and ran 10 million iterations and they were within 0-10% of each other. As @mttdbrd points out, this is in no way a "real life" test. Only benching this in production with the code actually functioning like it should before you truly know if there is a difference.

    Edit:

    Ok after tweaking my program to make sure I warmed up the hotspot compiler per @mttdbrd's document, and changing the program to be able to better tune the number of entries, I see some interesting results.

    With 1000 elements in the arrays:

    AtomicIntegerArray in 4224 millis
    AtomicBoolean[]    in 3546 millis    (always a little bit faster)
    

    However with 10 elements in the array:

    AtomicIntegerArray in 26506 millis
    AtomicBoolean[]    in 13263 millis  (much faster)
    

    Notice also the speed difference in general. It makes sense since there is more thread contention. 100 threads are much more likely to have to spin with 10 elements instead of 1000.

    What does this mean? That if you change from one to the other you might save yourself at most 1 nanosecond per operation. Might. So instead of worrying about the performance of the two, you should pick the pattern that is the cleanest and most easily maintained.

提交回复
热议问题