0

I know there are already tons of questions on this. But they don't clarify my doubts.

It is recommended here that to achieve thread safety, design your beans stateless. I don't understand it.

If I have a service class and it has only one state in it (and no other instance variables).

@Service
class MyService {

    @Autowired
    MyRepository repository;

    //business method that call repository methods

}

MyRepository has a default singleton scope. It has org.springframework.data.mongodb.core.MongoTemplate autowired. And that's the only instance variable I have in MyReporitory.

@Repository
class MyRepository {
    @Autowired
    MongoTemplate mongo;
    //methods that use MongoTemplate reference
}

So what is the deal here? Is service/repository thread safe?

Faraz
  • 6,025
  • 5
  • 31
  • 88

1 Answers1

1

If your repository reference is immutable (only autowired once, or set during service object construction) then your service bean is thread-safe.

Generally speaking, when multiple threads access the state of a bean simultaneously and that state is mutable (can change) you have potential threading issues. If the state is immutable and it's being read by multiple threads you need not worry about multi-threading issues.

Mustafa
  • 5,624
  • 3
  • 24
  • 40
  • I modified my question. Can you please answer that? – Faraz Sep 10 '18 at 13:14
  • @Desert If the MongoTemplate is thread safe tham the repository is thread safe. – Alexander Petrov Sep 10 '18 at 13:27
  • @AlexandarPetrov thanks for the response. Yes MongoTemplate is thread-safe https://stackoverflow.com/a/29913259/4828463 – Faraz Sep 10 '18 at 13:31
  • Alexandar, can you expound upon autowiring repository at several places. Lets say I have 2 service classes and I am autowiring MyRepository in both MyService1 and MyService2. Would that cause thread safety issues? – Faraz Sep 10 '18 at 13:33
  • Are you asking if spring Repositories thread-safe? You are wiring a single instance of the repository in both service instances. Spring manages repository thread-safety, see [answer to this](https://stackoverflow.com/questions/15965735/is-a-spring-data-jpa-repository-thread-safe-aka-is-simplejparepository-threa). – Mustafa Sep 11 '18 at 00:21
  • @Mustafa Thanks much for the help. That link to an answer does not answer my question. – Faraz Sep 11 '18 at 14:54
  • @Desert Every object that consists only of thread safe objects is by definition thread safe. The default "@Bean" definition is Singleton, this mean that any repository you bind through autowiring is actualy pointing to the same instance and since this instance is thread safe all is good. – Alexander Petrov Sep 11 '18 at 18:48
  • Thanks @AlexandarPetrov . You are answering autowiring MyRepository to 2 or more services right? – Faraz Sep 11 '18 at 19:10