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
source share