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.






I modified my question. Can you please answer that?

– Faraz Durrani
Sep 10 '18 at 13:14






@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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)