1

I know a similar question was asked several times, but I still can't find the only true answer.

public class SimpleMovieLister {

  private MovieFinder movieFinder;

  public void setMovieFinder(MovieFinder movieFinder) {
      this.movieFinder = movieFinder;
  }
  //getter
}

Why don't we make movieFinder volatile? Do Spring context make some damn-good magic to establish safe-publication of SimpleMovieLister? Or some threads can get NPE on movieFinder methods call?

Actually this answer clarifies the problem I'm talking about, but it doesn't state any proof or disproof of Spring's ability to prevent the issue. So I'm wondering if there's any 100 % right answer.

Community
  • 1
  • 1
d3rzKy
  • 142
  • 2
  • 9
  • answer may depend on usage/application of movieFinder – dev2d Dec 10 '13 at 13:05
  • You will only get a `NullPointerException` if the same object instance is used from multiple threads at the same time. This will only apply to startup of your application after that your object is fully initialized and you will not get a `NullPointerException`. If you access the bean before it is fully initialized you have another problem and you probably want constructor injection instead. – M. Deinum Dec 10 '13 at 13:06

1 Answers1

1

Spring makes sure that your eagerly initialized singletons can be safely accessed from any thread after the container initialization is complete.

If you have a prototype bean, created on demand by one thread and then published to other threads, you are on your own regarding thread safety.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436