Could anyone explain what is the difference between these examples?
Example # 1.
public class Main {
private Object lock = new Object();
private MyClass myClass = new MyClass();
public void testMethod() {
// TODO Auto-generated method stub
synchronized (myClass) {
// TODO: modify myClass variable
}
}
}
Example # 2.
package com.test;
public class Main {
private MyClass myClass = new MyClass();
private Object lock = new Object();
public void testMethod() {
// TODO Auto-generated method stub
synchronized (lock) {
// TODO: modify myClass variable
}
}
}
What should I use as a monitor lock if I need to take care about synchronization when modifying the variable?
Assuming that
Mainis not intended to be a “leaky abstraction”, here is minimal difference between the first and second examples.It may be better to use an
Objectrather than some other class because anObjectinstance has no fields and is therefore smaller. And theObject-as-lock idiom makes it clear that thelockvariable is intended to only ever used as a lock.Having said that, there is a definite advantage in locking on an object that nothing else will ever see. The problem with a
Mainmethod synchronizing on aMain(e.g.this) is that other unrelated code could also be synchronizing on it for an unrelated purpose. By synchronizing on dedicated (private) lock object you avoid that possibility.In response to the comment:
I think you are making an INCORRECT assumption – that
MyClassis the data structure that needs protecting. In fact, the Question doesn’t say that. Indeed the way that the example is written implies that the lock is intended to protect the entireMainclass … not just a part of its state. And in that context, there IS an obvious connection …The only case where it would be better to lock the
MyClasswould be if theMainwas a leaky abstraction that allowed other code to get hold of itsmyClassreference. That would be bad design, especially in a multi-threaded app.Based on the revision history, I’m pretty sure that is not the OP’s intention.