From documentation page:
Package java.util.concurrent.atomic Description:
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form
boolean compareAndSet(expectedValue, updateValue);
With many options available in atomic package like
AtomicBoolean
AtomicInteger
AtomicLongArray
etc, can I use these AtomicXXX and slowly get rid of volatile variables in my legacy code?
EDIT:
- Keep
volatile
for single write & multiple read operations in different threads (my conclusion after reading many articles), multi-writer, single-reader cases ( as per@erickson
comments) - Use
AtomicXXX
for multiple updates & multiple reads among multiple threads to avoidsynchronization
. Provide atomicity to volatile variables.
My thought process has been changed with @ericksoncomments.
volatile supports multiple write & single read` but can fail with multiple writes and multiple reads. I am confused on this concept.