Spring Safe-Publication

198 views Asked by At

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.

1

There are 1 answers

1
Marko Topolnik On

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.