简体   繁体   English

可运行的非最终字段是否不安全以提交给执行者?

[英]Is a runnable with non-final fields unsafe to submit to an 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);
        }
      }
    );
  }

Am I guaranteed to see "x = 5", or could I also see "x = 0" because the println is being executed in a different thread that might see the uninitialized value of x ? 我保证看到“x = 5”,或者我也能看到“x = 0”,因为println正在另一个可能看到未初始化的x值的线程中执行? I've never witnessed this happen, but I've been unable to find a guarantee that this doesn't happen (for example, if x were final , then it seems it will never happen). 我从来没有目睹过这种情况,但我一直无法保证不会发生这种情况(例如,如果xfinal ,那么它似乎永远不会发生)。

There are a number of "happens before" relationships defined in the latest JMM. 在最新的JMM中定义了许多“之前发生”的关系 One of these points is "starting a thread" and submitting to an executor carries the same guarantees as starting a thread (see the "memory consistency effects" in the javadocs). 其中一个点是“启动一个线程”并提交给执行程序,它具有与启动线程相同的保证(请参阅javadoc中的“内存一致性效果” )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM