When do we use AtomicReference
?
Is it needed to create objects in all multithreaded programs?
Provide a simple example where AtomicReference should be used.
AtomicReference class provides operations on underlying object reference that can be read and written atomically, and also contains advanced atomic operations. AtomicReference supports atomic operations on underlying object reference variable.
No, there is not. The additional power provided by AtomicReference is the compareAndSet() method and friends.
Atomic is a toolkit of variable java. util. concurrent. atomic package classes, which assist in writing lock and wait-free algorithms with the Java language. An algorithm requiring only partial threads for constant progress is lock-free.
An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
Atomic reference should be used in a setting where you need to do simple atomic (i.e. thread-safe, non-trivial) operations on a reference, for which monitor-based synchronization is not appropriate. Suppose you want to check to see if a specific field only if the state of the object remains as you last checked:
AtomicReference<Object> cache = new AtomicReference<Object>(); Object cachedValue = new Object(); cache.set(cachedValue); //... time passes ... Object cachedValueToUpdate = cache.get(); //... do some work to transform cachedValueToUpdate into a new version Object newValue = someFunctionOfOld(cachedValueToUpdate); boolean success = cache.compareAndSet(cachedValue,cachedValueToUpdate);
Because of the atomic reference semantics, you can do this even if the cache
object is shared amongst threads, without using synchronized
. In general, you're better off using synchronizers or the java.util.concurrent
framework rather than bare Atomic*
unless you know what you're doing.
Two excellent dead-tree references which will introduce you to this topic:
Note that (I don't know if this has always been true) reference assignment (i.e. =
) is itself atomic (updating primitive 64-bit types like long
or double
may not be atomic; but updating a reference is always atomic, even if it's 64 bit) without explicitly using an Atomic*
.
See the Java Language Specification 3ed, Section 17.7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With