Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic actions - what is meant by reads and writes?

Tags:

java

atomic

Its one thing I don't get about concurrency - threads and atomic-actions. According to docs.oracle these actions are specified as atomic:

  • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variables declared volatile (including long and double variables).

But at the same time docs.oracle asserts that incrementing a variable is not an atomic action. I thought that this was a write:

 private int number;
 number++;

Obviously I do not understand what is meant with "reads" and "writes".

Could someone explain this and give an example of "reads" and "writes"?

Edit: When doing this without synchronization the programs suffers from ´thread interference. SO I understand that its not atomic. But when I change another variable that belongs to an object that these threads share - there are NO interference whatsoever. The shared variable from this object is changed via a mutator.

like image 884
user2991252 Avatar asked Oct 17 '25 03:10

user2991252


1 Answers

In order to implement number++, the runtime needs to

  1. Acquire the current value of number (a read).

  2. Increment that value.

  3. Write that new value back to number (a write).

If another thread starts from 1 when you're at 2 then the final value for number will be incorrect since that thread will still be reading the original value.

If 1, 2 and 3 are executed as an atomic operation (i.e. a thread cannot start 1 until you've finished 3) then all will be well.

like image 137
Bathsheba Avatar answered Oct 18 '25 17:10

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!