1

I understand valid use cases for AtomicInteger but I am confused on how can AtomicBoolean, guarantee atomicity of two actions i. 'changing the boolean-value' and ii. execute the 'one-time-logic' eg initialize() in following often-quoted use-case for AtomicBoolean variable atomicInitialized:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

This operation will first set the atomicInitialized to true(if it is false) and then execute intialize() which isn't safe. It will guarantee that initialize() is only called once, but the second thread to hit the getAndSet() will not be delayed until the first thread has finished the initialisation. So, the AtomicBoolean while providing atomicity in updating boolean value doesn't really provide atomicity for entire 'if-block' and synchronize/lock mechanism has to be used for achieving complete atomicity. Hence, above often quoted, popular use-case, isn't really atomic!!

drop.in.ocean
  • 298
  • 2
  • 9
  • 1
    http://stackoverflow.com/questions/4501223/when-i-need-to-use-atomicboolean-in-java – JNL Oct 04 '13 at 17:15
  • AtomicBoolean is atomic, but not blocking. I haven't seen that example before, but yeah, it's broken. – kiheru Oct 04 '13 at 17:15
  • Yes. It only provides atomicity in handling the value of the Boolean value contained therein... It has nothing to do to "magically" make everything in 10 lines vicinity also atomic... – ppeterka Oct 04 '13 at 17:15
  • This is an incorrect usage of `AtomicBoolean`, but that doesn't mean that `AtomicBoolean` itself doesn't implement atomicity properly. – Louis Wasserman Oct 04 '13 at 17:16

1 Answers1

7

The "atomic" classes are meant to provide thread-safe access and manipulation for single variables. They are not meant for synchronization of entire blocks, such as the if block you have as an example here.

From the java.util.concurrent.atomic package description:

Atomic classes are designed primarily as building blocks for implementing non-blocking data structures and related infrastructure classes. The compareAndSet method is not a general replacement for locking. It applies only when critical updates for an object are confined to a single variable.

To synchronize the entire block, don't rely solely on the "atomic" classes. You must provide other synchronization code.

rgettman
  • 176,041
  • 30
  • 275
  • 357