简体   繁体   中英

Detect infinite loop inside a method

I have 2 methods in my main class

public class pol{

    public sub() {
         //... do this
         //... do this
         //... do this
         return result
    }

     public sub2()
         // calling method sub() here
         return result
     }

}

Is there any way so that i can detect that i wrote an infinite loop in sub() using method sub2() ?

We can take a scenario where i am loading a class using reflection in sub() and executing it over there ..

As long as they are running on a single thread, no. Operation will never return to sub2() if there is an infinite loop in sub().

If sub2() spins off a thread that starts a loop in sub() it might still not be possible. That might actually be a Halting Problem thing. Sub2() could interact with the thread sub() is in and kill it after a given time, given number of iterations, or some other criterion. If there is some state you know to check for that would cause an infinite loop sub2() could look for that state and kill sub() if it enters it but Thread has no .isInInfiniteLoop() method.

As @John M said as long as they are both running in the same thread the operation will never return back to sub()2 in case there is an infinite loop in sub() . However, you could detect it in sub()2 before entering the loop. This would be possible by assigning boolean values to every combination of the loop guard and see if it ever evaluates to false . Or you could create a truth table for every variable involved in the loop guard and see if the loop guard as a whole ever evaluates to false

如果您期望在某个时间之前sub()完成它的工作,除非它进入了无限循环,否则您可以在sub()中使用Timer或一些代码来将当前时间与开始时间进行比较,并在出现以下情况时停止sub()太多的时间过去了。

May it will help.

Just put conditions in the all loops you that put in sub().

Let me give you Example:

int i=0;
public void Sub(){
  //loop1
  while(true){
    ...
    ...
    if(i>1000){
    i=0;
    throw new Excepion();
    }
  }
  //loop2;
  //loop3; 
}

here you can add limit as per your need 1000 is just for example.

The easiest way to detect an infinite loop is to put a println statement (it can be anything) into your method. If the loop is infinite, then the println statement will repeatedly print.

If you make method sub2() print this statement, then you can use sub2() to detect the infinite loop in sub().

For debugging purposes, you can implement a counter and increment for each time the function is called. If the counter reaches a certain threshold, you can exit, call another function, print something to console, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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