Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can "while (i == i) ;" be a non-infinite loop in a single threaded application?

Tags:

java

People also ask

How can we prevent While true from being an infinite loop?

You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.

How do I stop a while loop running infinitely?

In for() loop: To avoid ending up in an infinite loop while using a for statement, ensure that the statements in the for() block never change the value of the loop counter variable. If they do, then your loop may either terminate prematurely or it may end up in an infinite loop.

Why is my while loop running infinitely?

Basically, the infinite loop happens when the condition in the while loop always evaluates to true. This can happen when the variables within the loop aren't updated correctly, or aren't updated at all. Let's say you have a variable that's set to 10 and you want to loop while the value is less than 100.

How do you stop an infinite loop in a thread?

The only way to stop a thread asynchronously is the stop() method.


double i = Double.NaN;

The API for Double.equals() spells out the answer: "Double.NaN==Double.NaN has the value false". This is elaborated in the Java Language Specification under "Floating-Point Types, Formats, and Values":

NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN. The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN. In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.


The value of i is then Invalid. "Not a Number".

After some googling, i found out that you CAN have NaN ( Not a Number ) in Java! So, a Float Pointing number is the Data Type and the Value is NaN. See here


double i = Double.NaN;

NaN is not equal to anything, including itself.


float i = Float.NaN;
while(i == i) ;
System.out.println("Not infinite!");

Since others said it's NaN I got curious about the official (JDK 6) implementation of Double.isNaN, and behold:

/**
 * Returns <code>true</code> if the specified number is a
 * Not-a-Number (NaN) value, <code>false</code> otherwise.
 *
 * @param   v   the value to be tested.
 * @return  <code>true</code> if the value of the argument is NaN;
 *          <code>false</code> otherwise.
 */
static public boolean isNaN(double v) {
    return (v != v);
}

I'm not sure, but I believe (i == i) is not atomic operation in multithreaded process, so if i value will be changed by other thread between pushes of it's value to stack on thread executing the loop, then that condition can be false.