Does spring garantee visibility of 'sleepInterval' and 'businessLogic' instance variables in case below?
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
}
}
}
}
I think there should be a visibility problem. But I couldn't reproduce it.
There won't be a visibility problem. The Java Memory Model guarantees that everything done (or visible due to a happens-before relationship) in one thread before a call to Thread.start will be seen by the thread that was started:
From the specification in the JLS section 17.4.5 :
A call to start() on a thread happens-before any actions in the started thread.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.