Thread runs an infinite operation which I have no control over. How to stop it?

Viewed 59

so I am making a java code testing web application and I am running each code execution in a seperate thread. The problem is that sometimes tests have a time limit or the student just writes an infinite while loop. I've tried to terminate my testing thread with "best practices" such as using interrupts but I have no control over the inner workings of my compilation function so I can't just tell the thread to look if it has been interrupted or not. I'd like advice on how to handle this situation better. Here is my bare bones example of what I want to achieve:


public class Main {
    public static void main(String[] args) {

        CodeExecutionThread cex = new CodeExecutionThread();

        cex.start();

        try {
            cex.join(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Thread should stop at this point.");

    }
}


class CodeExecutionThread extends Thread {

    public CodeExecutionThread() {

    }

    @Override
    public void run() {

        infinite_operation();

    }

    public void infinite_operation() {
        while(true) {
            System.out.println("thread active");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

1 Answers

I came accross the same problem more than once.

Probably not what you are looking for, but there is probably no better way than to use a flag inside the worker thread -- as described here for example: https://www.baeldung.com/java-thread-stop

When using a flag, there is of course a contract between the main thread and the worker -- you need to divide the infinite_operation into smaller chunks and check for the flag.

If you do not want that kind of contract or if it is not possible, consider using a process, which can be "safely" killed by OS (https://www.baeldung.com/java-process-api).

Related