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,537
  • 13
  • 47
  • 82

2 Answers2

1

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,101
  • 3
  • 28
  • 43
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;
}
Bringer128
  • 6,589
  • 2
  • 32
  • 59
  • 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) – Bringer128 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!) – Bringer128 Nov 11 '11 at 12:23