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.
Related
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.
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:
Is there a good way to forcefully stop a Java thread?
(7 answers)
Closed 2 years ago.
Is there a way to stop, kill or destroy a kid thread by the main thread who started it?
Everyone suggest to use some variable to check inside the thead itself, for exit when variable change state.
I can't do that, the thread is a very complex and big program and is not possible to foresee every conditions that could make it running in loop.
I need to force kill the thread from extern when time exceeded.
Thanks
No,
There is no safe way for one thread to forcibly kill another. There is no safe way for one thread to force another thread to do anything.
The problem is, threads communicate through shared variables. And, the author of any multi-threaded program must carefully "synchronize" the activities of the different threads, so that no thread can ever see the shared variables in some invalid state that was caused by the activity of another thread.
If you make it possible for a thread to be killed at any time, then there is no way you can ensure that the killed thread won't leave shared variables in an irreparably bad state.
If you can't work around the need to kill a "child," then you should re-write the code so that the child is a child process. Processes only share state in much more controlled ways, and it is much easier to write an application that can safely continue to execute after killing off a rogue child process.
This question already has answers here:
Do java threads get deleted when they finish
(3 answers)
Closed 7 years ago.
I want to know if a thread in java closes itself when run method ends.
I mean, I have a new thread declaration:
new Thread(new SubmitDataOnBackground(handler.getIDValue(), data, this.context)).start();
And then, in SubmitDataOnBackground I have this run method:
public void run() {
SubmitDataHandler submit = new SubmitDataHandler(ID, data, this.context);
submit.buildAndSubmitData();
}
After buildandSubmitData finishes, does the thread close itself or I have to add any code somewhere?
I am not sure if I am leaving a new thread opened each time I call this method or it is ok.
My application is a server so it will never ends because it is active the whole time. I just want to know the amount of threads is not outnumbered because it just creates new ones without closing the others when finish.
Threads close themselves after the run method has been called. Read this for further information https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
EDIT: If you want to avoid this behaviour, I recommend using ThreadPools.
Yes, a thread finishes when run() method execution ends. You can read more on threads and concurency in general here
One tip here - when using multiple threads that are started and finished all the time, it is a good idea to use a thread pool. That is because creating a thread is quite a heavy operation.
Threads are terminated after finishing their jobs (when the execution of run() ends). If you want to check, use isAlive().
Yes, threads are terminated after finishing their specified jobs (sequence of instructions) in run() method.
However, the thread object that has been created still exists, allowing you call it again with Thread.start() to create a new Thread.
If you want to be sure that your thread run method ends before continuing doing something more, try to use the method Thread.join() in the same place where you are working with threads.
Read this for further information about that:
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28%29
In order to actually make a Thread stop itself, the process is quite simple. All you need to do is simply let the run method run out and return.
public void run(){
// implement your code
// Just about to return and the Thread will then stop soon after
}
Note that the thread will not necessarily be declared finished immediately after the run method has finished, as the Java Virtual Machine (JVM) still needs to finish it off in the background, but it should terminate completely soon after.
In other words, when a normal Thread (also referred to as a user Thread) is created, it is expected that it will complete its work and not shut down permanetly. The JVM will not terminate until all user Threads have finished, or until a call is made to the System.exit() method, which terminates the JVM abruptly.
EDIT: System.exit() does not stop the JVM abruptly, it executes all the shutdown hooks first. Runtime.getRuntime().halt() stops the JVM without any further processing.
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.