简体   繁体   English

Java - 多线程

[英]Java - Multi Thread

I got this question in an interview, can some one clarify it..我在面试中遇到了这个问题,有人可以澄清一下吗..

**/**
 * Assuming a threaded environment, and without knowing anything else,
 * what is the potential problem with myMethod()?
 * Fix it in the simplest way.
 */
*/
public class ClumsyTest {
    private static final String FUBAR = "fubar";

    public boolean myMethod(final MyObject bar) {
        if (bar.getFoo() != null) {
            return bar.getFoo().equals(FUBAR);
        } else {
            return false;
        }
    }

    public interface MyObject {
        String getFoo();
        void setFoo(String o);
    }
}**

in 'myMethod', bar.getFoo() was verified twice.在“myMethod”中,bar.getFoo() 被验证了两次。 In multi thread environment, it is very well possible that value can change.在多线程环境中,值很可能会发生变化。 So, we need to verify it only once, and if we write as below,所以,我们只需要验证一次,如果我们这样写,

 **if (bar.getFoo().equals(FUBAR)) {
        return true;
    } else {
        return false;
    }**

it will throw null pointer exception if bar.getFoo() is null.如果 bar.getFoo() 是 null,它会抛出 null 指针异常。

How can we fix this method to check only once and by avoiding null pointer exception我们如何修复此方法以仅检查一次并避免 null 指针异常

It is quite simple actually.其实很简单。

Rather than doing bar.getFoo().equals(FUBAR) which risks NullPointerException , you gotta check it other way around as FUBAR.equals(bar.getFoo()) .而不是做bar.getFoo().equals(FUBAR)风险NullPointerException ,你必须以其他方式检查它作为FUBAR.equals(bar.getFoo()) And that's all there is to it.这就是它的全部。

So simply如此简单

    public boolean myMethod(final MyObject bar) {
        
        return FUBAR.equals(bar.getFoo());
        
    }

There's nothing wrong with the accepted answer.接受的答案没有错。 However, it works only for this specific case where equals() is used.但是,它仅适用于使用equals()的特定情况。 Had any other method of bar.getFoo() been used, we would not have been able to avoid the possible NullPointerException in the same way.如果使用了bar.getFoo()的任何其他方法,我们将无法以相同的方式避免可能的NullPointerException

The more generic answer is to store the result in a local variable.更通用的答案是将结果存储在局部变量中。

public boolean myMethod(final MyObject bar) {
    
    Object temp = bar.getFoo(); // temp can obviously be a more specific type
    if (temp != null) {
        return temp.toString().equals(FUBAR);
    } else {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM