When do we use AtomicReference?
Is it needed to create objects in all multithreaded programs?
Provide a simple example where AtomicReference should be used.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 set a specific field only if the state of the object has changed during processing:
Because of the atomic reference semantics, you can do this even if the
cacheobject is shared amongst threads, without usingsynchronized. In general, you’re better off using synchronizers or thejava.util.concurrentframework rather than bareAtomic*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 likelongordoublemay not be atomic; but updating a reference is always atomic, even if it’s 64 bit) without explicitly using anAtomic*.See the Java Language Specification 3ed, Section 17.7.