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?

1
  • I know this does not specifically address your question, but check out the package java.util.concurrent.atomic (Java 8). Commented Feb 27, 2015 at 19:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@iRaviiVooda In your example instructions, reg1 is effectively a constant/immutable. It will never change. So it's basically just memcopy <addr> 4.
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?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.