6

I wrote a program that automatically grades programming assignments submitted from students. Reflection is used to load classes and instantiate objects. Unintentional infinite loops are a common mistake in student assignments. A thread is assigned to each student submission. A monitor keeps track of the threads' running time and uses the stop() method to terminate threads that exceed the maximum time allowed. My program is working as intended, but the stop() method in java.lang.Thread is deprecated. I would greatly appreciate advice on a cleaner solution.

Thank you.

Jenks
  • 71
  • 4
  • What if your students use System.exit(0) by accident...? – Adam Nov 26 '14 at 22:37
  • 2
    @Adam that can be avoided with a proper security manager configuration: http://stackoverflow.com/questions/5401281/preventing-system-exit-from-api – reegnz Nov 26 '14 at 23:07
  • 1
    @lockstock none of those posts address the issue. I didn't ask why the stop method was deprecated, and my Thread instances aren't looping on some flag, nor will sending an interrupt solve the problem. – Jenks Nov 27 '14 at 01:26
  • Starting and controlling a process is surprisingly simple in Java. See `Java.Runtime.Process`. It's the only way of guarding against the most recalcitrant student! – Bathsheba Nov 29 '14 at 15:30

2 Answers2

6

stop() in java.lang.Thread was deprecated for good reasons: it didn't always work and could interfere with the workings of the JVM.

Your best bet is to run the programs in separate JVMs. You can then kill the processes if you need to.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

You should use an Executor service and the Future API. https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html

With futures you can do a future.get() and provide a timeout for how long the provided Callable is allowed to block. If the callable didnt finish, then after the timeout the get method will throw an exception. Then in the catch block you can cancel the execution with future.cancel(true);

reegnz
  • 837
  • 9
  • 16
  • I am unfamiliar with that API, but it looks like it will solve my problem. Thank you. – Jenks Nov 27 '14 at 01:27
  • 1
    Useful answer but .cancel(true) will not stop an infinite loop like while(true) {}, it just uses thread.interrupt() under the hood. – Adam Nov 27 '14 at 07:04
  • True, that was a mistake from my part, sorry... I guess a sandboxing solution would be ideal, or running in separate jvm-s. I was thinging of something like this: http://stackoverflow.com/questions/1715036/how-do-i-create-a-java-sandbox – reegnz Nov 27 '14 at 19:25