Ravindra babu
Ravindra babu

Reputation: 38950

Does volatile keyword lost its relevance due to AtomicXXX variables in multi-threaded applications?

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:

  1. 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)
  2. Use AtomicXXX for multiple updates & multiple reads among multiple threads to avoid synchronization. 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.

Upvotes: 3

Views: 162

Answers (1)

erickson
erickson

Reputation: 269877

Yes, an AtomicXXX instance provides the same visibility guarantees that you get from accessing a volatile field.

However, AtomicXXX do more than volatile fields, and accordingly, they are a bit more expensive to use. Specifically, they provide operations that are more like an optimized synchronized block than a volatile read or write. You increment-and-get, or compare-and-swap—multiple actions, atomically. Volatile variables don't provide any atomicity.

So, switching from volatile to AtomicXXX isn't necessarily a good move. Consider if it makes sense given how data are used, and perhaps do some profiling on a prototype to see what performance impact it will have.

Upvotes: 4

Related Questions