Hi. I don’t get why getName
method is equivalent to a method with synchronized keyword. If it locked on “this”, it would be the same but this one has monitor lock on “lock” field.
class Employee {
// shared variable
private String name;
private Object lock = new Object();
// method is synchronize on 'this' object
public synchronized void setName(String name) {
this.name = name;
}
// also synchronized on the same object
public synchronized void resetName() {
this.name = "";
}
// equivalent of adding synchronized in method
// definition
public String getName() {
// Using a different object to synchronize on
synchronized (lock) {
return this.name;
}
}
}