Search code examples
javamultithreadingtestngjava-threads

How to stop currentThread in Java?


I am running parallel tests using TestNg and I would like to stop/kill a thread at certain points in my script. There are many layers to this script so simply throwing exceptions all the way back to main() is not the best route in my case.

thread.stop() is working for me but it is deprecated so I would rather not use it and thread.interrupt() is not working for me because I would have to check in so many different places if the thread was interrupted. Here is a short, madeup example of what I mean:

        driverexec.navigateTo("http://www.google.com");
        
        xpath= "//input[@name='q111']";
        driverexec.typeByXpath("type search", xpath, "gorillas");
        System.out.println("gojng again");
        xpath= "//input[@name='btnK']";
        driverexec.clickByXpath("search google", xpath);

Now, each driverexec function could potentially fail, and I have a failure function set up for that. So basically every time my failure() function gets called, I would like to stop the current thread.

All of the example of seen if interrupt would cause me to have to place the line:

if (thread.interrupted()){
   
}

after every function call OR inside of my failure function. But even if I put it in my failure function, this just sets the flag. How can I actually STOP it?


Solution

  • You can just kill the thread from the inside, meaning throwing an Exception or Error that you never catch, and it just gets propagated upward the calling stack:

    public void failure() {
        // as you're using a test, an assertion error may be a suitable option
        throw new AssertionError("Test failure");
    }
    

    You also don't have to worry that your main method is affected by this, because exceptions from Threads other than the main-Thread will not be propagate all the way upwards.