Question

I want to know at which cases exactly should be used atomicity?

For example:

StringBuffer buffer = new StringBuffer();

may be

AtomicReference<StringBuffer> buffer = new AtomicReference<>(new StringBuffer());

But when it is really useful? Can somebody explain?

Was it helpful?

Solution 2

You will need AtomicReference when you have to update a reference which needs to be updated by a set of threads and read by other threads.

For instance, consider a processing job whose description and status is represented by some JobReport class; you have some threads processing a queue of jobs, and when one thread completes a job, it creates a JobReport object; in another set of threads, you want to know at one point in time, and as accurately as possible, which job was last processed: you need the latest JobReport.

In this case, all of these threads will share an AtomicReference<JobReport>; processing threads will write to it the report of the job they have just completed, while the reading, reporting threads will read from that reference.

(well, when I say "need"... There are other solutions to that scenario, but this is one of them)

OTHER TIPS

AtomicReference is about making two-three distinct operations on the reference itself execute atomically, such as compareAndSet, getAndSet, and others. It is not at all about the atomicity of operations on the referent (the object referred to by the reference).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top