Penalty of AtomicVariables over locks in Java

85 views Asked by At

For my current project, i try to use Atomic Integers and Atomic Booleans where ever possible when we have more than 1 thread accessing it. This helps in keeping the logic lock free(Internally i know it may still use locks) and the code much cleaner. The use case is mostly for configuration tags which may change abruptly.

I want to know what is the penalty performance wise of using Atomic Variables, will this invalidate the cache far too often and actually make my solution inferior than just using locks?

1

There are 1 answers

4
sodik On

atomic* classes does not use locks, it uses CAS (compare-and-set) to achieve thread-safety. in general they are faster then locking variant, however under very high contention they tends to be actually slower. if you want some analogy, it is something like optimistic and pessimistic locking in DB.

if you are interested in more details, you might want to check Java Performance: The Definitive Guide book.

ADD: With cache I assume you are referring to happens-before relationship. Here is quote from oracle tutorial:

The java.util.concurrent.atomic package defines classes that support atomic operations on single variables. All classes have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable.