synchronized对象设置为null [英] synchronized object set to null

查看:286
本文介绍了synchronized对象设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个主题 Thread1 Thread2

//Within Thread1     
synchronized(obj1)  
{  
    obj1 = null;  
}  

//Within Thread2  
synchronized(obj1)  
{  
    do something  
}   

如果jvm首先执行thread1并将obj1设置为null,那么thread2会立即看到该更改还是需要时间并且jvm仍然可以运行thread2同步块,因为obj1还没有空?

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.

这篇关于synchronized对象设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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