I have one thread1:
if(object != null){
object.play();
}
and another thread2 that can write null into object reference at any time.
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?
Absolutely – it could change the value of
objectwhile theplay()method is executing, if that’s what you mean. That wouldn’t cause an error in itself.Note that without synchronization or other memory barriers, thread2 could change the value of
objectwithout 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.