Reputation: 7647
Suppose I have DAO named Assignment which declare with @Document map with a mongo collection name Assignment.
Then I have a service bean for example AssigmentImpl which is in singleton scope, doing a update operation where it fetch the persisted DAO and update some with the REST input data for Assignment.
@Service
public class AssignmentImpl{
public Assignment updateAssignment(Assignment assignment){
Assignment assignmentExsisting = assignmentRepo.getAssignment(assignment.getId());
BeanUtils.copyProperties(assignment,assignmentExsisting);
assignmentRepo.save(assignmentExsisting);
}
}
Suppose multiple threads (users) doing the update operations to the different assignments.
Being AssignmentService is singleton it will return same copy to different users. How does it reference the Assignment object? If i say, since Assignment object is not singleton, it will return different object reference to AssignmentImpl when each users do update operation, is it right?
In that case user A might get assignment id 123 before do the update operation and when user B start do the update operation AssignmentImpl would change the assignment reference to different assignment id 456. In that case user A would update a totally different assignment. Is that be possible? If so how can we prevent it? Make the update operation synchronized or is there any other good solutions?
Upvotes: 1
Views: 89
Reputation: 22972
No, it won't be the way you are thinking, note that even service class is singlton every call to update won't overlap any other method call's execution as both will be executed in different threads created by server. So, the operation will take place as per the given assignment and two users' result won't get interchanged, why? because each thread executes method independently but the problem will arise when two threads tries to modify sate of shared element i.e. change value of object declared at class level in your service method.
For example, two buses are starting journey from point A to point B. Now, none of the buses have shared passengers (it's not possible right?), both have their own passengers and own fuel however the mechanism (repository and service) for both buses remains same.
You see two threads are not sharing anything here as far as I can tell, yes it uses repository bean but it doesn't modify it's state it will just send assignment to store and id to retrieve assignment.
Upvotes: 1