Is runnable with non-last fields unsafe for submission to the executor?

If I have code like the following:

  public void foo() {
    Executors.newSingleThreadedExecutor().submit(
      new Runnable() {
        int x = 5;
        public void run() {
          System.out.println("x = " + x);
        }
      }
    );
  }

I'm sure I see "x = 5", or can I also see "x = 0" because it printlnis running on another thread that can see an uninitialized value x? I have never seen this, but I could not find a guarantee that this will not happen (for example, if there xwere final, then it seems that this will not happen).

+4
source share
1 answer

"before before" , JMM. - " ", , (. " " javadocs).

+5

All Articles