Return value of assignment operator in parallel 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 if multiple threads calling method1() and method2() simultaneously on the same instance of Foo , can a call to method1 () ever return anything other than 1?

+34
java variable-assignment concurrency jls
Oct 12 2018-12-12T00:
source share
3 answers

JLS 15.26 states:

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

Ted Hopp's answer shows that Sun javac does not follow this behavior, perhaps as an optimization.

Due to the flow here, the behavior of method 1 will be undefined. If the Sun compiler makes the behavior persistent, it does not violate undefined behavior.

+10
Oct 12
source share

I think the answer depends on the compiler. Language indicates :

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

I believe that theoretically the value can be changed before the second (left) assignment occurs.

However, with the Sun javac compiler, method1 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 does not matter if the value stored in number changed before assigning to ret , since 1 , not number is assigned.

+15
Oct 12 '12 at 0:50
source share

Either the statement contains a volatile read, or it does not contain a volatile read. There can be no ambiguity here, since volatile reading is very important for programming semantics.

If javac can be trusted, we can conclude that the statement does not include a volatile reading of number . The value of the assignment expression x=y is actually just the value of y (after conversions).

It can also be deduced that

  System.out.println(number=1); 

does not include reading number

  String s; (s="hello").length(); 

does not include reading s

  x_1=x_2=...x_n=v 

does not include reading x_n, x_n-1, ... ; instead, the value of v assigned directly to x_i (after the necessary transformations through the types x_n, ... x_i

+5
Oct 12 '12 at 17:05
source share



All Articles