multithreading - externally ending infinite loop java -


i'm writing program mark algorithm submitted group of students. plan on copying algorithm method program , running see results; however, required algorithm not run more 10 seconds.

i constructed executorservice end algorithm works userinput algorithm (commented out) did not work infinite loop.

from know threads, interrupting require altering algorithm (add flag), , stopping thread depreciated, there other way end infinite loop without altering algorithm in anyway?

here's code:

public class testalgo{ private string move;  public static void main(string[] args){     testalgo testalgo = new testalgo();     testalgo.rungame(); }  public void rungame(){     cram game = new cram();     boolean start = game.startgame();       while (start){         executorservice executor = executors.newsinglethreadexecutor();/////         future<string> future = executor.submit(new task());/////         move = "";         try {             system.out.println("started..");             move = future.get(10, timeunit.seconds);             system.out.println("finished!");         } catch (timeoutexception e) {             future.cancel(true);             move = "timeout";             system.out.println("terminated!");         } catch (interruptedexception ie){             system.out.println("error: interruptedexception");         } catch (executionexception ee){             system.out.println("error: executionexception");         }         system.out.println("move: " + move);         executor.shutdownnow();            if (game.sendmove(move)) break;         game.printboard();         if (game.getmove()) break;         game.printboard();     } }  // public static string algorithm(){ //     while (true){ //infinite loop //         system.out.println("algo running..."); //     } //     return "test"; // }  public static string algorithm(){     scanner userinputscanner = new scanner(system.in);     system.out.print("please enter move: ");     string input = userinputscanner.nextline();     return input; }}  class task implements callable<string> { @override public string call() throws exception {     string move = testalgo.algorithm();     return move; }} 

google guava's simpletimelimiter should help. wrap executorservice within simpletimelimiter, , use callwithtimeout method specify given timeout period; handle uncheckedtimeoutexception indicate timeout reached. finally, call shutdown method of executorservice wrapped in simpletimelimiter.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -