1

I have read some info about volatile variables and their AtomicXXX counterparts, (e.g. AtomicBoolean).

But are there situations where I need to make the AtomicXXX object itself volatile, or is it never necessary?

Rox
  • 2,647
  • 15
  • 50
  • 85

2 Answers2

1

You don't need to - in fact, the atomic objects should really be set as final!!

Example:

private final AtomicInteger atomicInt = new AtomicInteger(0);

private volatile int volatileInt = 0;

public void doStuff() {
  // To use the atomic int, you use the setters and getters!
  int gotAnInt = atomicInt.getAndIncrement();

  // To use a volatile, access and set it directly. 
  int gotAnotherInt = volatileInt;
  volatileInt = someOtherInt;
}
  • Doesn´t the second assignment of volatileInt (volatileInt = someOtherInt;) include a read and a write and thus make the operation not atomic? – Rox Nov 11 '11 at 09:59
  • Yep, that is true. Apologies for implying otherwise - I'll remove the reference to atomicity! (FYI the assignment itself is atomic, but the read then write is not atomic) –  Nov 11 '11 at 10:03
  • So I should synchronize the doStuff() method to make it all atomic? To the topic: So if the AtomicXXX is not declared as final, I should theoretically declare it as volatile if it is shared between different threads? – Rox Nov 11 '11 at 11:23
  • Nope - the internals of the AtomicInteger class handle the synchronisation for you. You don't need to make it volatile (and in fact, a final volatile variable makes no sense!) –  Nov 11 '11 at 12:23
0

Read this for some tips and explanation when to use volatile. But basically if you are using AtomicXXX you DO NOT NEED to use volatile.

LordDoskias
  • 3,121
  • 3
  • 30
  • 44