弹簧,新线程中的实例变量可见性从@PostConstruct开始



在以下情况下,spring是否保证"sleepInterval"和"businessLogic"实例变量的可见性?

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class SomeService implements Runnable {
  @Value("${sleepInterval}")
  private Long sleepInterval;
  @Autowired
  private BusinessLogicService businessLogic;
  @PostConstruct
  public void postConstruct() {
      new Thread(this).start();
  }
  @Override
  public void run() {
      while (true) {
          try {
              Thread.sleep(sleepInterval);
              businessLogic.doSomeBusinessLogic();
          } catch (InterruptedException e) {
              //handle error
          }
      }
  }
}

我认为应该有一个可见性问题。但我无法重现它。

不会有可见性问题。Java 内存模型保证在调用 Thread.start 之前在一个线程中完成的所有操作(或由于发生前关系而可见(都将被启动的线程看到:

根据 JLS 第 17.4.5 节中的规范:

在线程上调用 start(( 发生在启动线程中的任何操作之前。

最新更新