I am writing my code in Java where I am creating an object and and accessing it in two different threads. My first thread1
thread calls some public methods on this object at runtime.
final Thread thread1 = new Thread(){
@Override
public void run() {
myObj.pubFunc1();
myObj.puFunc2();
myObj.pubFunc3();
}
};
I have another thread thread2
which might release this object and set it to null
like:
final Thread thread2 = new Thread(){
@Override
public void run() {
myObj.release();
myObj = null;
}
};
My question is if I should put check for null
around each statement in my thread1
like this?
final Thread thread1 = new Thread(){
@Override
public void run() {
if(myObj != null) {
myObj.pubFunc1();
}
if(myObj != null) {
myObj.pubFunc2();
}
if(myObj != null) {
myObj.pubFunc3();
}
}
};
OR only one check around all the statements is enough? The basic question that might originate from this is there is a lock around the object on which we have made a null check? How to handle this situation. What design pattern should I use to handle this situation.
NOTE: I do not want the three statements to be necessarily executed and I even do no want that the three statements form an atomic unit. I just want to perform an operation if the object I am performing the operation on is not null.
Aucun commentaire:
Enregistrer un commentaire