Spring,从@PostConstruct 开始的新线程中的实例变量可见性
Spring, instance variable visibility in new thread started from @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 之前在一个线程中完成的所有操作(或由于 happens-before 关系可见)将被启动的线程看到:
来自the JLS section 17.4.5中的规范:
A call to start() on a thread happens-before any actions in the started thread.
在以下情况下,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 之前在一个线程中完成的所有操作(或由于 happens-before 关系可见)将被启动的线程看到:
来自the JLS section 17.4.5中的规范:
A call to start() on a thread happens-before any actions in the started thread.