锁定在一个可变对象 - 为什么它被认为是一个坏的做法? [英] Locking on a mutable object - Why is it considered a bad practice?

查看:306
本文介绍了锁定在一个可变对象 - 为什么它被认为是一个坏的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅此回答。它说:


六个真正糟糕的例子;



...

锁定一个可变字段。例如synchronized(object){object = ...; }


锁定可变字段有什么问题?如果 object 被声明为 final 但是不是一个不可变的类?


< class =h2_lin>解决方案

这是一个坏主意,因为如果另一个线程更改了临界区中的引用,线程将不再看到相同的引用,因此他们不会在同样的对象,从而运行不受控制。示例:

 同步(lock1){
lock1 = new Object
sharedVariable ++;
}

假设有2个线程试图进入这个临界区。线程1进入,线程2等待。线程1进入,重新分配 lock1 并继续。现在线程2看到不同于线程1获得的锁,这也是免费的,所以它也可以进入临界区。乐趣接踵而至!



如果对象是 final ,则不能将引用重新分配给不同的对象,因此上述问题不再


See this answer. It says:

Six really bad examples;

...

locking on a mutable field. e.g. synchronized(object) { object = ...; }

What's wrong with locking on a mutable field? What if object was declared as final but was not an immutable class?

解决方案

It is a bad idea because if another thread changes the reference in the critical section, the threads will no longer see the same reference, and so they will not synchronize on the same object, thus running uncontrolled. Example:

 synchronized(lock1) {
     lock1 = new Object();
     sharedVariable++;
 }

Assume 2 threads are trying to enter this critical section. Thread 1 enters and thread 2 waits. Thread 1 goes in, reassigns lock1 and proceeds. Now thread 2 sees a different lock than what thread 1 acquired, which is also free, so it can also enter the critical section. Fun ensues!

If the object is final, you cannot reassign the reference to a different object, so the above problem no longer applies.

这篇关于锁定在一个可变对象 - 为什么它被认为是一个坏的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆