【发布时间】:2011-09-06 18:29:31
【问题描述】:
获取此代码:
public class MyClass {
private final Object _lock = new Object();
private final MyMutableClass _mutableObject = new MyMutableClass()
public void myMethod() {
synchronized(_lock) { // we are synchronizing on instance variable _lock
// do something with mutableVar
//(i.e. call a "set" method on _mutableObject)
}
}
}
现在,想象一下将 myMethod() 中的代码委托给您传递锁的某个辅助类
public class HelperClass {
public helperMethod(Object lockVar, MyMutableClass mutableVar) {
synchronized(lockVar) { // we are now synchronizing on a method param,
// each thread has own copy
// do something with mutableVar
// (i.e. call a "set" method on mutableVar)
}
}
}
可以重写“myMethod”以通过传递它的锁变量来使用 HelperClass,这样一切仍然是线程安全的吗?即,
public void myMethod() {
_helperObject.helperMethod(_lock, _mutableObject);
}
对此我不确定,因为 Java 会按值传递 lockVar,并且每个线程都会获得一个单独的 lockVar 副本(即使每个副本都指向堆上的同一个对象)。我想问题归结为“同步”关键字的工作原理——它是锁定变量还是变量引用的堆上的值?
【问题讨论】:
标签: java methods parameters locking synchronized