programing

자바의 무한 루프

nasanasas 2020. 9. 23. 07:42
반응형

자바의 무한 루프


whileJava에서 다음 무한 루프를 살펴보십시오 . 그 아래의 문에 대해 컴파일 타임 오류가 발생합니다.

while(true) {
    System.out.println("inside while");
}

System.out.println("while terminated"); //Unreachable statement - compiler-error.

그러나 다음과 같은 무한 while루프는 잘 작동하며 방금 조건을 부울 변수로 바꾼 오류가 발생하지 않습니다.

boolean b=true;

while(b) {
    System.out.println("inside while");
}

System.out.println("while terminated"); //No error here.

두 번째 경우에도 부울 변수 b가 true 이므로 컴파일러가 전혀 불평하지 않기 때문에 루프 뒤의 명령문에 분명히 도달 할 수 없습니다 . 왜?


편집 : 다음 버전은 while명백한 것처럼 무한 루프에 갇히지 만 if루프 내의 조건이 항상 false그렇고 결과적으로 루프가 반환되지 않고 컴파일러에 의해 결정될 수 있음에도 불구하고 그 아래의 명령문에 대해 컴파일러 오류가 발생 하지 않습니다. 컴파일 타임 자체.

while(true) {

    if(false) {
        break;
    }

    System.out.println("inside while");
}

System.out.println("while terminated"); //No error here.

while(true) {

    if(false)  { //if true then also
        return;  //Replacing return with break fixes the following error.
    }

    System.out.println("inside while");
}

System.out.println("while terminated"); //Compiler-error - unreachable statement.

while(true) {

    if(true) {
        System.out.println("inside if");
        return;
    }

    System.out.println("inside while"); //No error here.
}

System.out.println("while terminated"); //Compiler-error - unreachable statement.

편집 : 와 같은 것 if하고 while.

if(false) {
    System.out.println("inside if"); //No error here.
}

while(false) {
    System.out.println("inside while");
    // Compiler's complain - unreachable statement.
}

while(true) {

    if(true) {
        System.out.println("inside if");
        break;
    }

    System.out.println("inside while"); //No error here.
}      

다음 버전 while도 무한 루프에 빠집니다.

while(true) {

    try {
        System.out.println("inside while");
        return;   //Replacing return with break makes no difference here.
    } finally {
        continue;
    }
}

이는 문이 블록 자체 내에서 이전에 만나 finally더라도 블록이 항상 실행 return되기 때문 try입니다.


The compiler can easily and unequivocally prove that the first expression always results in an infinite loop, but it's not as easy for the second. In your toy example it's simple, but what if:

  • the variable's contents were read from a file?
  • the variable wasn't local and could be modified by another thread?
  • the variable relied on some user input?

The compiler is clearly not checking for your simpler case because it's forgoing that road altogether. Why? Because it's much harder forbidden by the spec. See section 14.21:

(By the way, my compiler does complain when the variable is declared final.)


According the specifications, the following is said about while statements.

A while statement can complete normally iff at least one of the following is true:

  • The while statement is reachable and the condition expression is not a constant expression with value true.
  • There is a reachable break statement that exits the while statement.\

So, the compiler will only say that the code following a while statement is unreachable if the while condition is a constant with a true value, or there is a break statement within the while. In the second case, since the value of b is not a constant, it doesn't consider the code following it to be unreachable. There's a whole lot more information behind that link to give you more details on just what is and what isn't considered unreachable.


Because true is constant and b can be changed in the loop.


Because analyzing variable state is hard, so the compiler has pretty much just given up and let you do what you wish. Additionally, the Java Language Specification has clear rules about how the compiler is allowed to detect unreachable code.

There are many ways to trick the compiler - another common example is

public void test()
{
    return;
    System.out.println("Hello");
}

which wouldn't work, as the compiler would realize that the area was unreacable. Instead, you could do

public void test()
{
    if (2 > 1) return;
    System.out.println("Hello");
}

This would work since the compiler is unable to realize that the expression will never be false.


The latter is not unreachable. The boolean b still has the possibility of being altered to false somewhere inside the loop causing an ending condition.


My guess is the variable "b" has possibility to change its value, so compiler think System.out.println("while terminated"); can be reached.


Compilers aren't perfect - nor should they be

The responsibility of the compiler is to confirm syntax - not to confirm execution. Compilers can ultimately catch and prevent many run time problems in a strongly typed language - but they cannot catch all such errors.

The practical solution is to have batteries of unit tests to complement your compilers checks OR use object oriented components for implementing logic that are known to be robust, rather then relying on primitive variables and stop conditions.

Strong Typing and OO : increasing compiler's efficacy

Some errors are syntactical in nature - and in Java, the strong typing makes a lot of run time exceptions catchable. But, by using better types, you can help your compiler to enforce better logic.

If you want the compiler to enforce logic more effectively, in Java, the solution is to build robust, required objects that can enforce such logic, and using those objects to build up your application, rather than primitives.

A classic example of this is the use of the iterator pattern, combined with Java's foreach loop this construct is less vulnerable to the type of bug you illustrate than a simplistic while loop.


The compiler is not sophisticated enough to run through the values that b may contain (though you only assign it once). The first example is easy for the compiler to see it will be an infinite loop because the condition is not variable.


I'm surprised your compiler refused to compile the first case. That seems strange to me.

But the second case isn't optimized to the first case because (a) another thread might update the value of b (b) the called function might modify the value of b as a side effect.


Actually I don't think anyone got it QUITE right (at least not in the original questioner's sense). The OQ keeps mentioning:

Correct, but irrelevant, as b is NOT being changed in the loop

But it doesn't matter because the last line IS reachable. If you took that code, compiled it into a class file and handed the class file to someone else (say as a library), they could link the compiled class with code that modifies "b" through reflection, exiting the loop and causing the last line to execute.

This is true of any variable that isn't a constant (or final which compiles to a constant in the location where it's used--sometimes causing bizarre errors if you recompile the class with the final and not a class that references it, the referencing class will still hold the old value without any errors whatsoever)

I've used the ability of reflection to modify non-final private variables of another class to monkey-patch a class in a purchased library--fixing a bug so we could continue developing while we waited for official patches from the vendor.

By the way, this may not actually work these days--although I've done it before, there is a chance that such a small loop will be cached in the CPU cache and since the variable is not marked volatile the cached code may never pick up the new value. I've never seen this in action but I believe it's theoretically true.


It is simply because the compiler doesn't to too much baby sitting work, though it is possible.

The example shown is simple and reasonable for compiler to detect the infinite loop. But how about we insert 1000 lines of code without any relationship with variable b? And how about those statements are all b = true;? The compiler definitely can evaluate the result and tell you it is true eventually in while loop, but how slow it will be to compile a real project?

PS, lint tool definitely should do it for you.


From the compiler's perspective the b in while(b) could change to false somewhere. The compiler just doesn't bother checking.

For fun try while(1 < 2), for(int i = 0; i < 1; i--) etc.


Expressions are evaluated at run time so, when replacing the scalar value "true" with something like a boolean variable, you changed a scalar value into a boolean expression and thus, the compiler has no way to know it at compilation time.


If the compiler can conclusively determine that the boolean will evaluate to true at run-time, it will throw that error. The compiler assumes that the variable you declared can be changed (albeit we know here as humans it will not).

To emphasize this fact, if variables are declared as final in Java, most compilers will throw the same error as if you substituted for the value. This is because the variable is defined at compile time (and cannot be changed at run-time) and the compiler can therefore conclusively determine that the expression evaluates to true at run-time.


The first Statement always result in an infinite loop because we have specify a constant in condition of while loop, where as in second case compiler assume that, there is possibility of change of value of b inside loop.

참고URL : https://stackoverflow.com/questions/8570243/infinite-loops-in-java

반응형