Bean with singleton scope and with states
Bean with singleton scope and with states
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
.
MyRepository
org.springframework.data.mongodb.core.MongoTemplate
MyReporitory
@Repository
class MyRepository
@Autowired
MongoTemplate mongo;
//methods that use MongoTemplate reference
So what is the deal here? Is service/repository thread safe?
1 Answer
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.
@Desert If the MongoTemplate is thread safe tham the repository is thread safe.
– Alexandar Petrov
Sep 10 '18 at 13:27
@AlexandarPetrov thanks for the response. Yes MongoTemplate is thread-safe stackoverflow.com/a/29913259/4828463
– Faraz Durrani
Sep 10 '18 at 13:31
@Desert then the repository is thread safe.
– Alexandar Petrov
Sep 10 '18 at 13:32
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 Durrani
Sep 10 '18 at 13:33
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I modified my question. Can you please answer that?
– Faraz Durrani
Sep 10 '18 at 13:14