66061

externally ending infinite loop java

I'm writing a program that will mark an algorithm submitted by a group of students. I plan on copying their algorithm method into the program and running it to see the results; however, it is required that the algorithm not run for more than 10 seconds.

I constructed a ExecutorService to end the algorithm which works for the userInput algorithm (commented out) but did not work for an infinite loop.

From what I know about threads, interrupting it would require altering the algorithm (add a flag), and stopping a thread is depreciated, so is there any other way to end the infinite loop without altering the algorithm in anyway?

Here's the 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 is running..."); // } // return "test"; // } public static String algorithm(){ Scanner userInputScanner = new Scanner(System.in); System.out.print("Please enter your move: "); String input = userInputScanner.nextLine(); return input; }} class Task implements Callable<String> { @Override public String call() throws Exception { String move = TestAlgo.algorithm(); return move; }}

Answer1:

Google Guava's SimpleTimeLimiter should help. Simply wrap your ExecutorService within the SimpleTimeLimiter, and then use the callWithTimeout method to specify a given timeout period; handle the UncheckedTimeoutException to indicate that the timeout was reached. Finally, call the shutdown method of the ExecutorService that was wrapped in the SimpleTimeLimiter.

Answer2:

You could finish your thread in the while loop:

public static String algorithm(){ long start = System.currentTimeMillis(); long end = start + 10*1000; // 10 seconds? while (System.currentTimeMillis() < end){ //not-so-infinite loop System.out.println("Algo is running..."); } return "test"; }

But if you don't want to modify the algorithm() method, you could check this, or this.

Answer3:

As an alternative to running the untrusted code in a thread in your JVM, consider firing off a separate process using ProcessBuilder. You can then use the Process destroyForcibly method to terminate it.

Recommend

  • Using C, to print out an array from textFile
  • Limiting the number of search suggestions, android
  • Angular2 - Template reference inside NgSwitch
  • Display java JPanel in a JFrame
  • How to Cache Real-time Data?
  • How to rebase a series of branches?
  • Spring Data JPA custom method causing PropertyReferenceException
  • req.body is undefined - nodejs
  • Possible to stop flickering java tooltip in heavyweight mode?
  • output of program is not same as passed argument
  • Join two tables and save into third-sql
  • sending/ receiving email in Java
  • JSON with duplicate key names losing information when parsed
  • Display Images one by one with next and previous functionality
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Matplotlib draw Spline from multiple points
  • Akka Routing: Reply's send to router ends up as dead letters
  • XCode can't find symbols for a specific iOS library/framework project
  • Calling of Constructors in a Java
  • Compare two NSDates in iPhone
  • Transpose CSV data with awk (pivot transformation)
  • Cannot Parse HTML Data Using Android / JSOUP
  • Use group_by to filter specific cases while keeping NAs
  • How to delete a row from a dynamic generate table using jquery?
  • log4net write single file for each call to log.info
  • Proper way to use connect-multiparty with express.js?
  • Benchmarking RAM performance - UWP and C#
  • Acquiring multiple attributes from .xml file in c#
  • JTable with a ScrollPane misbehaving
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
  • How can I remove ASP.NET Designer.cs files?
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • failed to connect to specific WiFi in android programmatically
  • java string with new operator and a literal
  • How can I use threading to 'tick' a timer to be accessed by other threads?