[英]Java Synchronized block
Is it valid to update a reference in an synchronized block of that reference? 在参考的同步块中更新参考是否有效? eg:
例如:
Synchronized(list)
{
list = new ArrayList();
}
When you write 当你写
synchronized (list)
The lock is an object , not the variable/field list
. 锁是一个对象 ,而不是变量/字段
list
。
If you do 如果你这样做
synchronized (list) {
list = new ArrayList<>();
}
you are creating a new object, and reassigning a variable/field - but you have not changed the lock - the lock is still the same object it was before. 您正在创建一个新对象,然后重新分配一个变量/字段-但您尚未更改锁-锁仍然是以前的对象。
Yes, it is completely valid but what would you achieve by doing this? 是的,它是完全有效的,但是这样做会带来什么呢? Besides, threads gain lock on object instance not on variable which holds object reference so even if you reassign
list
with some other instance, current thread has already taken lock on the previous object. 此外, 线程获得对象实例的锁定,而不是持有对象引用的变量的锁定,因此即使您用其他实例重新分配
list
,当前线程也已经锁定了上一个对象。
To clarify more, let's say list
was assigned value val1
. 为了进一步说明,假设为
list
分配了值val1
。 Then a thread1
takes lock on val1
(which is pointed by variable list
), now other threads can't take lock on val1
(because they are waiting for lock on instance val1
not on reference list
) even though thread1
has re-instantiated list
. 然后,
thread1
锁定val1
(由变量list
指向),现在即使thread1
重新实例化了list
,其他线程也无法锁定val1
(因为它们正在等待实例val1
不在参考list
上的锁定)。
Better would be to clear the list
inside synchronized
block instead of re-initializing it. 最好是清除
synchronized
块中的list
而不是重新初始化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.