Return value of assignment operator in concurrent code

后端 未结 3 833
爱一瞬间的悲伤
爱一瞬间的悲伤 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:36

    Either the statement contains a volatile read, or it doesn't contain a volatile read. There cannot be any ambiguity here, since volatile read is very important to program semantics.

    If javac can be trusted, we can conclude that the statement doesn't involve a volatile read of number. The value of an assignment expression x=y is really just the value of y (after conversions).

    We can also deduce that

        System.out.println(number=1);
    

    does not involve reading number

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

    does not involve reading s

        x_1=x_2=...x_n=v
    

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

提交回复
热议问题