[英]Checking for an object being null in Java
I am writing my code in Java where I am creating an object and and accessing it in two different threads. 我正在用Java编写代码,在其中创建对象并在两个不同的线程中访问它。 My first
thread1
thread calls some public methods on this object at runtime. 我的第一个
thread1
线程在运行时在此对象上调用一些公共方法。
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: 我有另一个线程
thread2
,它可能会释放该对象并将其设置为null
例如:
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? 我的问题是我是否应该像这样在我的
thread1
每个语句周围放置null
检查?
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.
如果我要对其执行操作的对象不为null,我只想执行一项操作。
The design your propose is flawed. 您提出的设计存在缺陷。 Imagine this execution:
想象一下这个执行:
myObj = new MyObject();
if (myObjec != null)
=> all good, object is not null if (myObjec != null)
=>一切正常,则对象不为null myObj.release(); myObj = null;
myObj.release(); myObj = null;
myObj.release(); myObj = null;
myObj.pubFunc1();
myObj.pubFunc1();
=> Boom, NPE. I think you only have 2 options: 我认为您只有两种选择:
myObj
to make the if/pubFunc calls atomic myObj
的访问,以使if / pubFunc调用变为原子 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. 注意:我假设您已经知道可见性问题,并且
myObj
已正确发布/同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.