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

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

问题描述

请参阅此答案.它说:

六个非常糟糕的例子;

...

锁定可变字段.例如同步(对象){ 对象 = ...;}

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

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

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++;
 }

假设有 2 个线程试图进入这个临界区.线程 1 进入,线程 2 等待.线程 1 进入,重新分配 lock1 并继续.现在线程 2 看到的锁与线程 1 获取的锁不同,它也是空闲的,因此它也可以进入临界区.乐趣随之而来!

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!

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

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

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

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