I just got a question that I can\'t answer.
Suppose you have this loop definition in Java:
while (i == i) ;
What is the type of
i == i
is not atomic. Proved by such program:
static volatile boolean i = true;
public static void main(String[] args) throws InterruptedException
{
new Thread() {
@Override
public void run() {
while (true) {
i = !i;
}
}
}.start();
while (i == i) ;
System.out.println("Not atomic! i: " + i);
}
Update Here is one more example of not-infinite loop (no new threads are created).
public class NoNewThreads {
public static void main(String[] args) {
new NoNewThreads();
System.gc();
int i = 500;
System.out.println("Still Running");
while (i == i) ;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
Thread.sleep(1000);
System.exit(0);
}
}
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
I was surprised to not see this solution:
while (sin(x) == sin(x)) //probably won't eval to true
In response to a comment, try running this:
double x = 10.5f;
assert (x == asin(sin(x)));
x should always equal the arcsine(sin(x)) in theory, but in practice it doesn't.
double i = Double.NaN;
NaN is not equal to anything, including itself.
Think of Nan as the equivalent of exception but uses a magic value within a calculation. Because a calculation failed - eg square root of a negative, divide by zero etc - it makes no sense in comparing them against anything else. After all if divide by zero is a nan is it equivalent to the square root of -2 or square root of -3 ?
Nan allows a calculation that includes a step that returns an invalid answer to complete without introducing extra exceptions. To verify the answer is value simply test for non nandness ( is that's word if not I bags it) via Float.isNan() o equivalent.
Not infinite loop, one thread :)
import static B.*;
public class A {
public static void main(String[] args) {
System.out.println("Still Running");
while (i == i) ;
}
}
public class B {
public static int i;
static {
System.exit(0);
}
}