Search code examples
javaconcurrencyvariable-assignmentjls

Return value of assignment operator in concurrent code


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?


Solution

  • The JLS 15.26 specifies:

    There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

    Ted Hopp's answer shows that Sun's javac doesn't follow this behaviour, possibly as an optimisation.

    Due to the threading here, the behaviour of method1 would be undefined. If Sun's compiler makes the behaviour constant then it doesn't break from the undefined behaviour.