Java null检查

jel*_*ion 4 java concurrency null

我有一个thread1:

if(object != null){
   object.play();
}
Run Code Online (Sandbox Code Playgroud)

而另一个thread2可以写入nullobject随时参考.

我会同时运行这些线程.我知道thread2可以objectnull检查后重写参考,这将抛出NullPointerException.是否有可能thread2改写object后的参考NullPointerException检查?

Jon*_*eet 6

在NullPointerException检查后,是否有可能让thread2重写对象引用?

绝对 - 它可以改变方法执行object时的值play(),如果这就是你的意思.这不会导致错误本身.

请注意,如果没有同步或其他内存障碍,thread2可能会更改object没有thread1注意到不确定时间段的值.

很难说你应该做什么,而不知道代码的更大目标.


wes*_*ton 5

简单的synchronized例子:

/**
To maintain thread safety, only access this through getter and setter
or other synchronized method
**/
private ObjectType object;

public synchronized void setObject(ObjectType object) {
  this.object = object;
}

public synchronized ObjectType getObject() {
  return object;
}

public void doPlay() {
  final ObjectType obj = getObject();
  //here, thread 2 can change "object", but it's not going to affect this thread
  //as we already safely got our reference to "object" in "obj".
  if(obj != null){ 
   obj.play(); 
  }
}

public synchronized void alterativeDoPlay() {
  //the difference here is that another thread won't be able to change "object"
  //until the object's play() method has completed.
  //depending on the code in play, this has potential for deadlocks, where as
  //the other `doPlay` has zero deadlock potential.
  if(object != null){
   object.play(); 
  }
}
Run Code Online (Sandbox Code Playgroud)