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

Java Spring,新线程中的实例变量可见性从@PostConstruct开始,java,spring,concurrency,visibility,postconstruct,Java,Spring,Concurrency,Visibility,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 Ru

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之前,在一个线程中完成的所有事情(或由于“先于发生”关系而可见的事情)都将被启动的线程看到:

根据中的规范:

对线程的start()调用发生在已启动线程中的任何操作之前


你为什么认为会有问题?这是一个类访问同一类的字段的方法。@Vasan实际上我已经预料到了潜在的NPE。Spring在单个线程中初始化了所有bean,并从另一个线程访问了自动连接的值(非最终和非易失性)。但NPE从未发生过。在规范中找到此部件。谢谢