It's preferable to maintain a lock object and synchronize on that, such as:
public class MyClass {
private final Object lock = new Object();
public void reconnect() {
synchronized(lock) {
....
}
}
....
}
The reason is that when you use the synchronized keyword in a method signature, you're actually synchronizing on your MyClass
instance. The problem is, any other code outside your class could also do that. For instance,
public class SomeOtherClass {
public void go(final MyClass myClass) {
synchronized(myClass) {
wait(Integer.MAXIMUM_VALUE);
}
}
}
Now if some other thread wants to call myClass.reconnect()
, they can't, because SomeOtherClass
has taken the lock on the myClass
instance.