How can infinite loops be terminated in dynamically loaded classes?

I wrote a program that automatically sorts programming tasks submitted by students. Reflection is used to load classes and create objects. Unintended endless cycles are a common mistake in student assignments. A stream is assigned to each student submission. The monitor monitors the running time of the threads and uses the stop() method to terminate threads that exceed the maximum allowable time. My program works as intended, but the stop() method in java.lang.Thread deprecated. I would really appreciate some advice on cleaner solutions.

Thanks.

+6
source share
2 answers

stop() in java.lang.Thread deprecated for valid reasons: it did not always work and could interfere with the JVM.

It is best to run programs in separate JVMs. Then you can kill the processes if you need to.

+5
source

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

With futures, you can do future.get () and provide a timeout for how long the provided Callable can block. If the called does not finish, then after the timeout the get method will throw an exception. Then, in the catch block, you can cancel execution using future.cancel (true);

+1
source

Source: https://habr.com/ru/post/978763/


All Articles