Return value of assignment operator in concurrent code

BeeOnRope picture BeeOnRope · Oct 12, 2012 · Viewed 12.4k times · Source

Given the following class:

class Foo {
  public volatile int number;

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

  public int method2() {
    int ret = number = 2;
    return ret;
  }
}

and given multiple threads calling method1() and method2() concurrently on the same Foo instance, can a call to method1() ever return anything other than 1?

Answer

Ted Hopp picture Ted Hopp · Oct 12, 2012

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.