Reputation: 21
Say you have 2 or more threads which share an object A.
object A has a list inside of it, which contains another object B
Object A List Object B
Now the threads modify/read Object B
Question is, what should be synchronized? Object A as they both access it, or Object B since that's what they read/modify
I cannot seem to find the answer to my question anywhere.
Thanks in advance
Upvotes: 2
Views: 115
Reputation: 12006
Going a simplest and safest route, you need to synchronize on the outmost object in your object hierarchy, which should be operated in a atomic manner.
In your example, it seems like you need to synchronize on a list (unfortunately, I can't be sure what's really you going to do without actual code).
Here's sample code:
class B {
}
class A {
private final List<B> listOfBs = new ArrayList<B>();
void add(B b) {
synchronized (listOfBs) {
listOfBs.add(b);
}
}
List<B> getSnapshot() {
List<B> copy = new ArrayList<B>();
synchronized (listOfBs) {
copy.addAll(listOfBs);
}
return copy;
}
}
Please, note that you need to declare list as final
to eliminate possibility that some code may change reference to a list which violate atomicity:
// will make add() and getSnapshot() not mutually exclusive, thus violating atomicity of operations
...
listOfBs = new ArrayList<B>();
...
Reading Java concurrent programming tutorial will help.
Upvotes: 2
Reputation: 758
If you modify object B through one of its methods, then you should make that method (or the part that does the writing) synchronized.
Upvotes: 0