What operations in Java are considered atomic?

What operations in Java are considered atomic?

+68
java multithreading atomicity
Jan 21 2018-11-11T00:
source share
3 answers
  • all assignments of primitive types except long and double
  • all link assignments
  • all assignments of mutable variables
  • all operations java.concurrent.Atomic * classes

and maybe something more. Take a look jls .

As noted in the comments, atomicity does not imply visibility. Therefore, while another thread is guaranteed not to see the partially written int , it will never see the new value.

Operations with long and double are found on common 64-bit atomic CPUs, although there is no guarantee. See also this function request .

+85
Jan 21 2018-11-11T00:
source share

In Java, reading and writing 32-bit or less is guaranteed to be atomic.
By atom we mean that each action takes place in one step and cannot be interrupted. Thus, when we have multithreaded applications, the read and write operations are thread safe and do not require synchronization.

For example, the following code is a safe stream:

 public class ThreadSafe { private int x; public void setX(int x) { this.x = x; } } 
+4
Jan 30 '11 at 2:25
source share

It would seem that the longs assignments are atomic, based on this method in AtomicLong.java:

 public final void set(long newValue) { value = newValue; } 

Note the lack of any synchronization.

0
Oct 18 '13 at 4:48 on
source share



All Articles