Java空检查 [英] Java null check
问题描述
我有一个 thread1
:
if(object != null){
object.play();
}
和另一个 thread2
可以随时将 null
写入对象
。
and another thread2
that can write null
into object
reference at any time.
我会同时运行这些线程。我知道 null
后可以重写对象
并且会抛出 NullPointerException
。在 NullPointerException
之后 thread2
重写 object
检查?
I will run these threads at same time. I know thread2
can rewrite object
reference after the null
check and that will throw NullPointerException
. Is it possible for thread2
to rewrite object
reference after NullPointerException
check?
推荐答案
在NullPointerException检查后,thread2是否可以重写对象引用? p>
Is it possible to for thread2 to rewrite object reference after NullPointerException check ?
绝对可以改变 object
的值,而 play()
方法正在执行,如果这是你的意思。
Absolutely - it could change the value of object
while the play()
method is executing, if that's what you mean. That wouldn't cause an error in itself.
请注意,没有同步或其他内存障碍,thread2可以更改 object
没有thread1注意到一个不确定的时间段。
Note that without synchronization or other memory barriers, thread2 could change the value of object
without thread1 noticing for an indeterminate period of time.
很难说你应该做什么,没有任何其他知识的代码的更大的目的。
It's hard to say what you ought to do, without any other knowledge of the bigger aim of the code.
这篇关于Java空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!