synchronized object set to null(同步对象设置为空)
问题描述
我有两个线程 Thread1
和 Thread2
//Within Thread1
synchronized(obj1)
{
obj1 = null;
}
//Within Thread2
synchronized(obj1)
{
do something
}
如果 jvm 首先执行 thread1 并将 obj1 设置为 null,那么 thread2 会立即看到该更改还是需要一些时间,并且 jvm 仍然可以运行 thread2 同步块,因为 obj1 尚未为 null?
If jvm first executes thread1 and sets obj1 to null, then will thread2 see that change immediately or will it take time and jvm could still run the thread2 synchronized block since obj1 is not yet null?
推荐答案
这几乎肯定会破坏同步抽象——我不相信 thread2
会立即看到变化.您永远不应该更改您正在同步的对象的引用,更不用说将其设置为 null
,这将在任何进一步尝试对其进行同步时导致 NullPointerException
.
This will almost certainly break the synchronization abstraction -- I wouldn't be confident that thread2
will see the change immediately. You should never change the reference of the object you're synchronizing on, much less set it to null
, which will cause a NullPointerException
on any further attempts to synchronize on it.
这篇关于同步对象设置为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:同步对象设置为空


- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01