Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What operations in Java are considered atomic?

What operations in Java are considered atomic?

like image 412
robinmag Avatar asked Jan 21 '11 07:01

robinmag


People also ask

What operations are atomic in Java?

Atomic operations are those operations that ALWAYS execute together. Either all of them execute together, or none of them executes. If an operation is atomic, then it cannot be partially complete, either it will be complete, or not start at all, but will not be incomplete.

Are assignments atomic in Java?

Variables shared between multiple threads (e.g., instance variables of objects) have atomic assignment guaranteed by the Java language specification for all data types except for long s and double s.

What are atomic variables?

You can think of these are wrapper of primitive types boolean, integer and long, with the difference: they are designed to be safely used in multi-threaded context. They are called atomic variables because they provide some operations that cannot be interfered by multiple threads.


1 Answers

  • all assignments of primitive types except for long and double
  • all assignments of references
  • all assignments of volatile variables
  • all operations of java.concurrent.Atomic* classes

and maybe something more. Look at the jls.

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

The operations on long and double are on common 64 bit CPUs atomic as well, although there's no guarantee. See also this feature request.

like image 101
maaartinus Avatar answered Sep 25 '22 04:09

maaartinus