Spring,实例变量在新线程中的可见性从@PostConstruct开始 [英] Spring, instance variable visibility in new thread started from @PostConstruct
本文介绍了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()发生在启动的线程中的任何操作之前。
这篇关于Spring,实例变量在新线程中的可见性从@PostConstruct开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文