Killing java thread in test

I am writing a kind of programming tutorial (it will be a Java repository on github), where users can clone repos and write their own code in empty methods to solve algorithmic problems. After they write their code, they can run unit tests to verify that they are correct and complete after less than a certain time (to make sure they find the most effective solution). This way my repo will contain many classes with empty methods and all non-empty unit tests to check the code that users will write.

What I do in JUnit tests looks something like this:

// Problem.solveProblem() can be a long running task Thread runner = new Thread(() -> Problem.solveProblem(input)); runner.start(); try { Thread.currentThread().sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (runner.isAlive()) { fail("Your algorithm is taking too long."); runner.stop(); } 

Now, if the user writes a non-optimized algorithm, the test will fail, but the runner thread will continue to run (and so will the test thread) until it completes, which can happen after a few minutes, although I call running.stop() . Therefore, I have tests that can last minutes instead of seconds, as I would like.

I know how to gracefully kill a thread in Java, but in this case I do not want users to care about multithreading problems (for example, checking / updating shared variables): I just want them to write only code to solve the problem.

So my question is: is there a way to suddenly kill a thread in Java? If not, is there any other approach that I could take to achieve my goal?

Thanks Andrea

0
source share
2 answers

Use Thread.currentThread().getThreadGroup() to iterate over. Thread.stop is a brute force method, but in your case it will probably work if you call Thread.interrupt -edit- I read it too quickly and thought you were causing sleep in your generated threads. While re-reading, I see that you are simply doing this in your main thread, as RealSkeptic commented on this post, it is vague and probably unlikely that interrupt will solve the problem

0
source

You can use ScheduledExecutorService with a timeout:

 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); Future<?> future = executor.schedule(() -> Problem.solveProblem(input)); try { future.get(500, TimeUnit.MILLISECONDS); } catch (Exception e){ fail("Your algorithm is taking too long."); future.cancel(true); } 

Some refinement may be required, but you will get the basics.

0
source

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


All Articles