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

原学程将引见Spring,虚例变质在新线程中的看来性从@PostConstruct开端的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

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

成绩描写

鄙人里的情形下,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之前1个线程中完成的一切操纵(或者因为产生之前的闭系而看来)皆将被开动的线程瞅到:

去自the JLS section 一七.四.五中的标准:

对于线程挪用Start()产生在开动的线程中的所有操纵之前。

佳了闭于Spring,虚例变质在新线程中的看来性从@PostConstruct开端的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。