在下面的情况下,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/