Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java null check

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?

like image 668
jellyfication Avatar asked Dec 08 '22 20:12

jellyfication


2 Answers

Is it possible to for thread2 to rewrite object reference after NullPointerException check ?

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.

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.

like image 155
Jon Skeet Avatar answered Dec 29 '22 21:12

Jon Skeet


Simple synchronized example:

/**
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(); 
  }
}
like image 27
weston Avatar answered Dec 29 '22 23:12

weston