-1
public class Hello {
static volatile int a;
public static void main(String[] args) {

    a=200;
    a=100;
    a=a+1;

}}

the byte code are below

0 sipush 200
3 putstatic #2 <jvm_test/Hello.a>
6 bipush 100
8 putstatic #2 <jvm_test/Hello.a>
11 getstatic #2 <jvm_test/Hello.a>
14 iconst_1
15 iadd
16 putstatic #2 <jvm_test/Hello.a>
19 return

the a=200 composed by sipush 200 and putstatic #2 instead of one operation. so, why we say this is atomic

testlove
  • 11
  • 1

1 Answers1

4

sipush pushes the number 200 to the stack, and putstatic assigns the value on top of the stack to the class's static field.

The reason these two bytecode instructions can be viewed together as atomic is because "the stack" is the current thread's stack; other threads have their own stacks, so they can't interfere with what's on the stack in this thread in between those two instructions.

If the temporary storage space for the number 200 was some shared memory that was writable by other threads, then it would indeed not be thread-safe.

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • 1
    +1. Somewhat related - as [this answer](https://stackoverflow.com/a/4756578/6577998) also notes, atomicity does not imply visibility. Maybe that is another point of confusion for OP. – mnestorov Mar 24 '21 at 12:27