Closed AndroidDeveloperLB closed 2 years ago
Atomic wrappers use volatile operations in their get() and set() methods. So, until you use compareAndSet
, getAndSet
etc, they are the same (but Atomic has extra indirection).
@Miha-x64 I couldn't find now explanation of what you wrote, and also no benchmark between the two. Can you please show me where you've got it?
Also, even if it's wrapped, doesn't it mean the compiler will still optimize it to be the same, and let the developer be able to use the extra feature it has?
Can you please show me where you've got it?
By looking into Atomic* sources. Get and set are just plain accessors.
doesn't it mean the compiler will still optimize it to be the same
Java or Kotlin compilers definitely won't because this could affect too much.
Runtime theoretically could do this but I've never ever heard about object field scalarization/inlining. There are even separate Atomic*FieldUpdater
utility classes useful to optimize this on your own.
@Miha-x64 Sure if the compiler doesn't do it, runtime might. I actually use Atomic* much more often than volatile, because there is a good chance for extra operations that could be used badly when using volatile. Using volatile it could give you the illusion that you are doing everything safely... That's why I was surprised to see this inspection.
Anyway, thanks.
Yep, Atomic functionality is much wider. If you use compareAndSet
, getAndSet
, getAndIncrement
etc and the inspection is still triggered, please report a false-positive.
@Miha-x64 OK thank you!
As I remember, AtomicBoolean is lock-free and uses CPU operation that's especially for it, so it's quite efficient. Maybe the most efficient. Why would we want to replace it with volatile instead?
Have you performed some benchmarks to see that volatile is better?