Miha-x64 / Mikes_IDEA_extensions

IntelliJ IDEA: missing parts.
Apache License 2.0
34 stars 7 forks source link

Question: What's the reason for the inspection of "Atomic can be replaced with volatile" ? #14

Closed AndroidDeveloperLB closed 2 years ago

AndroidDeveloperLB commented 2 years ago

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?

Miha-x64 commented 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).

AndroidDeveloperLB commented 2 years ago

@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?

Miha-x64 commented 2 years ago

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.

AndroidDeveloperLB commented 2 years ago

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

Miha-x64 commented 2 years ago

Yep, Atomic functionality is much wider. If you use compareAndSet, getAndSet, getAndIncrement etc and the inspection is still triggered, please report a false-positive.

AndroidDeveloperLB commented 2 years ago

@Miha-x64 OK thank you!