Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic Operations and multithreading

Recently I was reading a tutorial, in that I came across a statement that says..

"The Java language specification guarantees that reading or writing a variable is an atomic operation(unless the variable is of type long or double). Operations variables of type long or double are only atomic if they declared with the volatile keyword."

AtomicInteger or AtomicLong that provides methods like getAndDecrement(), getAndIncrement() and getAndSet() which are atomic.

I got confused a bit with the above statement.. could you please clarify when to use AtomicInteger or AtomicLong classes.

like image 937
MaheshVarma Avatar asked May 24 '13 07:05

MaheshVarma


People also ask

What are atomic operations?

Atomic operations are sequences of instructions that guarantee atomic accesses and updates of shared single word variables. This means that atomic operations cannot protect accesses to complex data structures in the way that locks can, but they provide a very efficient way of serializing access to a single word.

Are atomic operations thread-safe?

Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization. An atomic operation is executed in one single machine-level operation.

What is an atomic operation example?

An example of atomic operation is instruction execution, usually an instruction feed to the execution unit can't be stopped in the middle. Yet, a statement in high level language results in multiple instructions. It is the root cause of non-atomic operations.

Can atomic operations be interrupted?

Methods for ensuring an operation is atomicIf an operation requires multiple CPU instructions, then it may be interrupted in the middle of executing. If this results in a context switch (or if the interrupt handler refers to data that was being used) then atomicity could be compromised.


1 Answers

Doing a = 28 (with a being an int) is an atomic operation. But doing a++ is not an atomic operation because it requires a read of the value of a, an incrementation, and a write to a of the result. As a result, if you used a++ to implement a thread-safe counter, you could have two threads reading the value concurrently (26 for example), then have both increment it and writing it concurrently, resulting in 27 as a result, instead of 28.

AtomicInteger solves this issue by providing atomic operations like the ones you listed. In my example, you would use incrementAndGet() for example, which would guarantee the end value is 28 and not 27.

like image 102
JB Nizet Avatar answered Oct 09 '22 03:10

JB Nizet