Return value of assignment operator in concurrent code

后端 未结 3 829
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 06:50

Given the following class:

class Foo {
  public volatile int number;

  public int method1() {
    int ret = number = 1;
    return ret;
  }

  public int me         


        
3条回答
  •  庸人自扰
    2020-12-05 07:28

    I think the answer depends on the compiler. The language specifies:

    At run-time, the result of the assignment expression is the value of the variable after the assignment has occurred.

    I suppose that theoretically the value could be changed before the second (leftmost) assignment occurs.

    However, with Sun's javac compiler, method1 will will turn into:

    0:   aload_0
    1:   iconst_1
    2:   dup_x1
    3:   putfield        #2; //Field number:I
    6:   istore_1
    7:   iload_1
    8:   ireturn
    

    This duplicates the constant 1 on the stack and loads it into number and then into ret before returning ret. In this case, it won't matter if the value stored in number is modified before assignment to ret, because 1, not number is being assigned.

提交回复
热议问题