This question already has answers here:
How to properly stop the Thread in Java?
(9 answers)
How do you kill a Thread in Java?
(17 answers)
Closed 1 year ago.
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?
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.
Related
This question already has answers here:
Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?
(5 answers)
When does Java's Thread.sleep throw InterruptedException?
(8 answers)
Closed 1 year ago.
I am aware that ignoring an InterruptedException is actually a bad practice. But let's assume in my case it is necessary: it is a utils method in a deep place, which is called by different threads. Please also assume it is not possible to rethrow.
If my only option is to tell the system "ok, I will not sleep any further, but I cannot kill this thread myself. I will finish my job and hope that my caller takes care of your interruption request", is this the correct way of doing it?
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// ignore
Thread.currentThread().interrupt();
}
Does the method interrupt() do anything else other than resetting the interrupted flag?
Please also assume it is not possible to rethrow.
Impossible; you can always rethrow. throw new RuntimeException("unhandled", e); is never a compile time error - that should be your default choice for "I have no idea what this exceptions means or I cant be bothered to handle it". It's perfectly fine: It ensures that the code will be rolled up properly, you want that to happen when exceptions you can't handle / weren't expecting (heh) occur.
However, in this case, uniquely, 'I did not expect it' also means it cannot possibly happen.
InterruptedException
Note that InterruptedException cannot ever happen unless some code is explicitly doing it. You do not get interrupted when the system is running low on resources and needs you to clean up. You do not get interrupted because some code in java core or any third party library decided to interrupt you for funsies. You do not get interrupted when the user hits CTRL+C, or goes into the task manager and clicks 'end process'.
There is only one way to be interrupted, and it is when some java code running in your JVM process runs: yourThread.interrupt();.
Presumably, there are only two options:
[A] You never do this. The point is moot. Rethrow that thing using throw new RuntimeException(e); - you're writing code that is literally going to never ever run, stop worrying about it.
[B] You invoked interrupt(), explicitly. I assume it wasn't because the cat strolled on the keyboard :) - You had some intent by doing it. So, what is the intent? Whatever you intended to happen, program it in the catch block. The usual options are either to abort a thread entirely (so, just return;), or if you have a loop that sleeps, checks something, sleeps again, etc - to recheck (a poor man's wait/notify setup, in other words), or to re-read some configuration or otherwise re-perform some initialization procedure. It's up to you. There is no described style or rule.
Does the method interrupt() do anything else other than resetting the interrupted flag?
Yes, it returns true or false depending on whether it was up or not. But this is completely pointless. Everything in java that can throw InterruptedException +lowers that flag first_. There is therefore absolutely no point whatsoever in lowering the flag in the catch block - it has already been lowered if you ever get there. You EITHER get the flag raised on you, OR you get an InterruptedException (the flag is there because not everything throws InterruptedEx). Note that if your thread is sleeping due to some sleeping op that is not declared to throws InterruptedException, then it may interrupt or not - it depends on the OS capabilities. For example, if you're waiting for network traffic (e.g. calling read() on an InputStream derived from a java.net.Socket or whatnot), then interrupted the thread may either do nothing at all other than raise the flag, or, it will actually end up shutting down the threadsleep. In that case, the code in that InputStream will lower the flag and ends up throwing some sort of IOException (because it can't throw InterruptedException; InterruptedException is checked, and read() doesn't declare it).
Note that if the flag is raised, and you invoke any method that is specced to throw InterruptedException, said method will act IMMEDIATELY, it never goes to sleep in the first place. It lowers the flag and throws InterruptedException, instantly.
Therefore you rarely need to check the flag - very few threads lack a looping construct and very few threads will chug on for a long time without ever invoking anything that will end up invoking Thread.sleep() or obj.wait() somewhere along the line.
NB: The intent of the interrupted() method is to use it as the sole condition in a busy loop that doesn't otherwise call any code that would throw InterruptedException. e.g.:
while (!Thread.interrupted()) {
doSomethingThatNeverSleeps();
}
that'd be the whole body of your run() method. That will keep running forever and make your CPU fans make the laptop take off, at least until some other code tells the thread to call it a day by invoking .interupt(). As I said, rare that you need this construct, but that's what it is for.
This question already has answers here:
What is thread Safe in java? [duplicate]
(2 answers)
Closed 2 years ago.
I have a program where I want my threads to make a sort of update to something else, but since I start all of the threads at the same time, they make the update at the same time which defeats the purpose because they all overwrite each other. I want a thread to update something, have that something use it quickly, then get changed afterwards. Is there a way to allow any thread to go first and then have the others wait? It feels like I can't do anything because if I change the thread class, then all of the threads will perform the change and still execute at the same time. I am using a GUI too, so I can't just use Thread.Sleep between each thread's start call. I don't think any code would help the question, I just want to know if there's a way to block all threads but one, or delay each thread from getting to the same line of code at the same time, since they all change a variable.
Use a synchronized block for this purpose. When a block of code is wrapped in synchronized, only a single thread can access it, and other threads wait for their turns
synchronized(this)
{
// your line of code
}
This question already has answers here:
How do you kill a Thread in Java?
(17 answers)
Closed 6 years ago.
I need to call an external method which sometimes takes indefinite time to complete.
void doMyStuff(){
// do my stuff
// work is being done by doStuff thread
externalMethod(); // This is external and sometimes takes hours
// I need to check if current thread is interrupted and then return after a certain time
}
However, I can't afford to keep a thread engaged, so I need to terminate the process after a fixed time. I can interrupt the doStuff thread from an external thread with the help of Websphere's WorkManager API. But only sending the interrupt signal is useless unless the interrupted thread handles it.
I want to return the doStuff thread to thread pool after a certain time no matter whether the extenalMethod() returns or not. How can this be done?
Use myThread.isInterrupted() to see if the Thread is interrupted or not.
void doMyStuffs(){
//do my stuffs
System.out.println(myThread.isInterrupted());
}
This question already has answers here:
How to stop uninterruptible threads in Java
(6 answers)
Closed 9 years ago.
It is a widely known fact that one shall not stop running processes using Thread.stop().
Usually the manuals and tutorials suggest using Thread.interrupt() or some boolean variable instead, and checking from inside the code for that interrupt or variable.
But if I have a library method which takes a very long time to execute sometimes, and I want to give user an ability to stop that process? And library does not give me a mechanisms to do it (does not check thread interrupted status, and no "stop!" variables)?
And, to add to the bad things, there is either no source code for library, or it is just too big to edit it and add checks at appropriate places.
It seems that Thread.stop() is the only solution here. Or maybe there is some workaround?
Why you do not try to use sleep(long timeout) when are waiting for some condition and if had not success, you simple "return" from the thread?
Probably your thread is running in a while (booleanVariable) { },
if it is, you could set this variable as volatile, and the thread controller set it as false.
Think of the Thread.stop() like the System.exit(value), it works, but when you have some bug making you thread stop/vm exit, will be much more harder to find it out.
If practical in your situation, spawn another process and treat that as the unit of work, rather than a thread. Process killing is much more deterministic, though devoting a process to what used to be a thread's work might be too heavyweight for your situation.
The only solution better than using Thread.stop() is to use the library in a seperate thread which you can kill to stop it.
You may want to look for different handles of the function you are running, for example if its IO you can try to close any open connections/streams. If you are stuck with this library (IE can't find one that has better interruption mechanics) Thread.stop() is your only way of stopping the thread.
Thread.stop() is deprecated from java 4 onwards..I read an article to stop a thread by wrapping the call to the library in an separate class that implements InterruptibleChannel which is part of java.nio.
Interruptibleclasses has close() method, through which another thread can call it asynchronously.
This question already has answers here:
How to abort a thread in a fast and clean way in java?
(15 answers)
Closed 2 years ago.
I'm in the process of writing a piece of code that connects to a server spawns a bunch of threads using that connection and does a bunch of "stuff".
There are certain instances where the connection fails and I need to stop everything and start from scratch with a new object.
I wanted to clean up after the object but calling thread.stop on the threads, but this method is seemingly deprecated.
What is the recommended alternative to doing this? Should I write my own cleanup and exit method for each of the threads? Set the thread to null? or something else?
Assuming your threads are reasonably under your control - i.e. they're not calling anything which is going to potentially wait forever without your code executing - I would shut it down with a simple (but thread-safe - use volatile!) flag.
See this article for an example in C# - the Java equivalent should be easy to work out. Calling interrupt won't have any effect until the thread next waits, and stop can leave your app in a hard-to-predict state. Wherever possible, go for a clean, orderly shutdown instead.
Use your_thread.interrupt and check in your thread if Thread.interrupted() return true. If so, close your thread properly.
private Thread m_CleanupThread = null;
public void threadCleanUp(){
m_CleanupThread = new Thread(this);
m_CleanupThread.Start();
}
This thread will terminate and garbage collector will do the rest.