java - Spring,新线程中的实例变量可见性从@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 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中的规范:

A call to start() on a thread happens-before any actions in the started thread.

关于java - Spring,新线程中的实例变量可见性从@PostConstruct开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49742762/

相关文章:

java - 在 Intellij 的插件部分中找不到 Drool 插件

java - 在 Android 应用程序中存储 MongoDB 数据库凭据

html - thymeleaf : How to get first element of list without iterating?

scala - Akka、 future 和临界区

java - 这是Java中的内存泄漏吗?

尝试编译应用程序时出现 javax.net.ssl.SSLHandshakeException

java - 干净的代码——在 Java 中压缩代码的最佳方式

java - 随机找不到类路径资源

spring - Spring 中 Hibernate 数据库生成错误

javascript - 说 Node.js 和 JavaScript 提供基于事件循环的并发模型是不正确的吗?