Why does making the lock object private encapsulate the lock so that client code cannot acquire it ?
Object’s Intrinsic Lock
public class A{
private final Set<Integer> set = new HashSet<Integer>();
public synchronized void addInt(int i){
set.add(i);
}
}
Private Lock
public class B{
private final Set<Integer> set = new HashSet<Integer>();
public void addInt(int i){
synchronized(set){
set.add(i);
}
}
}
Well, another class can’t access
setat all, because it’s private. Of the many things everyone else can’t do because they don’t have access to that reference, synchronizing on it is one.If a getter returns that reference directly (without wrapping or copying the object), someone else can synchronize on it, defeating the benefits of a lock on a private object.