开发者

Is it possible for a==a to evaluate false for some variable a in Java?

开发者 https://www.devze.com 2023-02-16 17:42 出处:网络
I\'ve been posed this slightly obscure but interesting question about the开发者_如何学Go behavoir of Java. Any ideas?Yep, Try this...

I've been posed this slightly obscure but interesting question about the开发者_如何学Go behavoir of Java. Any ideas?


Yep, Try this...

public class Main
{
  public static void main(String[] args)
  {
    double a = Double.NaN;
    if( a == a ) System.out.println("equal");
  }
}

http://www.ideone.com/K0d2j


Yes, for float or double NaNs (but not Float or Double). Section 4.2.3 of the JLS 3rd Ed. I believe IEEE 754 defines the operation that way. Those are the only cases.


As giddy said, concurrency can mess it up. I just tried this:

public class Madness {

    private static volatile long a = 0;

    public static void main(String[] args) {

        long good = 0;
        long bad = 0;

        new Thread() {
            {
                setDaemon(true);
            }

            public void run() {
                while (true)
                    a++;
            }
        }.start();

        long print = System.currentTimeMillis() + 1000;

        while (true) {
            if (a == a)
                good++;
            else
                bad++;
            if (System.currentTimeMillis() > print) {
                System.out.println(String.format("%d / %d", good, bad));
                print = System.currentTimeMillis() + 1000;
            }
        }

    }

}

Output was:

19936409 / 382
38360780 / 640
56895813 / 898
75827635 / 1159
94500958 / 1423
113184503 / 1701
131711068 / 1960
150423573 / 2239
168898106 / 2509

Admittedly, this is a case specifically designed to cause this. Removing the volatile on a changes things. I see some initial "bad" hits, but then it seems to be all good. I haven't investigated, but I have a feeling it's something to do with hot spot optimizing the code after some number of iterations.


The code for Double.isNaN()

static public boolean isNaN(double v) {
    return (v != v);
}

This sounds like an interview questions. A similar questions when is x == x + 0 false which has more answers. ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号