0

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?

mastercool
  • 463
  • 12
  • 35
  • It sounds like you want to use an exception. This is pretty much the purpose of an exception. You throw it, and it bubbles back up to where you handle it. You don't even have to keep re-throwing it, just don't handle it. – matt Mar 19 '21 at 12:58
  • You cannot STOP a thread. Stopping a thread is a cooperative process and you can ask the thread to be stopped with the interrupted flag. So, the code running in the thread should check the flag and process an InterruptedException. Java std support this flag for all blocking operations like ServerSocket.assept, Socket read/write, BlokingQueue.put/take, Thread.sleep/wait, etc.etc. And if you have your own code which calculates something for a long time (milliseconds, seconds...) you have to put if (thread.interrupted()) ( throw new InterruptedException(); } into it to have the code interruptable – AnatolyG Mar 19 '21 at 13:06
  • But it look that you don't need to interrupt some long running method in the middle, you need to check some result and stop the scenario. In this case just throw appropriate exception as Lino just suggested. – AnatolyG Mar 19 '21 at 13:14

1 Answers1

2

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.

Lino
  • 19,604
  • 6
  • 47
  • 65