Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 863
BeeOnRope Avatar asked Oct 12 '12 00:10

BeeOnRope


People also ask

What is the return value of assignment operator?

The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.

What does the assignment operator return in C?

The assignment operators in C and C++ return the value of the variable being assigned to, i.e., their left operand. In your example of a = b , the value of this entire expression is the value that is assigned to a (which is the value of b converted into the type of a ).

Is == an assignment operator?

What is the difference between = (Assignment) and == (Equal to) operators. The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not. If so, it returns true.

What assignment operator assigns a value to a variable?

The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value.


1 Answers

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.

like image 111
Ted Hopp Avatar answered Sep 30 '22 12:09

Ted Hopp