0

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.

Yurii Bondarenko
  • 3,460
  • 6
  • 28
  • 47
  • Why do you expect there'll be a problem? It is a method of a class accessing fields of same class.. – Vasan Apr 09 '18 at 22:51
  • @Vasan Actually I've expected potential NPE. Spring initialized all beans in a single thread, and autowired value (non-final and non-volatile) accessed from another thread. But NPE never happened. – Yurii Bondarenko Apr 09 '18 at 22:54

1 Answers1

1

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.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79