Search code examples
javaatomic

When Exactly Should Atomicity be used? When is it Really Useful?


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?


Solution

  • 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)