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

人气:313 发布:2022-10-16 标签: java visibility concurrency spring postconstruct

问题描述

在下面的情况下,Spring是否保证‘sleepInterval’和‘Business Logic’实例变量的可见性?

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

来自the JLS section 17.4.5中的规范:

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

970