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.
The design your propose is flawed. Imagine this execution:
myObj = new MyObject();
if (myObjec != null)
=> all good, object is not null myObj.release(); myObj = null;
myObj.release(); myObj = null;
myObj.pubFunc1();
=> Boom, NPE. I think you only have 2 options:
myObj
to make the if/pubFunc calls atomic or you save a local copy of the object - this may or may not be acceptable depending on your use case:
public void run() { MyObject localObj = myObj; if (localObj != null { //NOTE: myObj may have been released localObj.pubFunc1(); localObj.puFunc2(); localObj.pubFunc3(); } }
Note: I assume that you are aware of visibility issues and that myObj
is properly published/synchronized.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.