2

Are Array read/writes atomic in nature?

int[] arr = new int[10];
int[8] = 4; // This is what I'm interested in

In the above code, the second line should generate two Machine Instructions like

reg1 = reg_containing_arr_address + 32
Memcopy reg1 4

Some posts on stack overflow saw that these are atomic. Can anyone explain me how they are?

Dunes Buggy
  • 1,779
  • 1
  • 21
  • 41
  • I know this does not specifically address your question, but check out the package java.util.concurrent.atomic (Java 8). – Kode Charlie Feb 27 '15 at 19:50

1 Answers1

2

The components (elements) of arrays are variables.

The result of an array access expression is a variable of type T, namely the variable within the array selected by the value of the index expression.

According to this answer, writes and reads of int variables are atomic. Since your array is of type int, reads and writes to it are atomic.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • I clearly understand that `int` variables are atomic, and read/writes to that variable are atomic (i.e. the second instruction in my generated machine code). But there is one more instruction of generating the variable's address in setting the array's value. I really don't think this explains how and what atomic instruction is generated when setting the array value. – Dunes Buggy Feb 27 '15 at 21:02
  • @iRaviiVooda In your example instructions, `reg1` is effectively a constant/immutable. It will never change. So it's basically just `memcopy 4`. – Sotirios Delimanolis Feb 27 '15 at 22:57
  • I'm exactly looking for what you are saying. With my knowledge, I don't see how it is a constant. Lookup in arrays is O(1), but its actually 2 instructions like I showed. Can you tell me the instructions generated for my instruction? – Dunes Buggy Feb 27 '15 at 23:18
  • @iRaviiVooda Conceptually, it's as if the first instruction didn't exist. It's impossible (failing a buggy OS) that `reg1` can be different between the first and second instructions. – Sotirios Delimanolis Feb 27 '15 at 23:24