Stopping a Thread in Java? [duplicate]

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?


Asked by: Cadie244 | Posted: 21-01-2022






Answer 1

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.

Answered by: Grace512 | Posted: 22-02-2022



Answer 2

Use your_thread.interrupt and check in your thread if Thread.interrupted() return true. If so, close your thread properly.

Answered by: Rubie601 | Posted: 22-02-2022



Answer 3

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.

Answered by: Daniel113 | Posted: 22-02-2022



Similar questions

multithreading - Java: Stopping a thread that has run for too long?

Say I've got something like this public void run(){ Thread behaviourThread = new Thread(abstractBehaviours[i]); behaviourThread.start(); } And I want to wait until abstractBehaviours[i] run method has either finished or run for 5000 milliseconds. How do I do that? behaviourThread.join(5000) doesn't seem to do that afaik (something is wrong with my code and I've put it down to that)...


multithreading - Java thread not stopping even when while loop is done

I have a client <-> server application. The problem is when I click a button "Exit" it does not kill the entire thread. It kills the process, but the thread still remains active. But if I click the "X" button the JOptionPane.showConfirmDialog is stopping everything, so I would like the button to do the same (to be terminated). P.P. The "Exit" button starts a JSwingWorker which is calling disconnect()


multithreading - Java: Stopping a thread that has run for too long?

Say I've got something like this public void run(){ Thread behaviourThread = new Thread(abstractBehaviours[i]); behaviourThread.start(); } And I want to wait until abstractBehaviours[i] run method has either finished or run for 5000 milliseconds. How do I do that? behaviourThread.join(5000) doesn't seem to do that afaik (something is wrong with my code and I've put it down to that)...


multithreading - Stopping looping thread in Java

I'm using a thread that is continuously reading from a queue. Something like: public void run() { Object obj; while(true) { synchronized(objectsQueue) { if(objectesQueue.isEmpty()) { try { objectesQueue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } ...


multithreading - Stopping a specific java thread

I have a button "addCashier" which is creating a thread called "Cashier" now this thread is just simply generating orders every 4 seconds, a while(true) loop in the run() method of the thread. All is good there, but now I want to add a button to simulate cashiers logging off. I added a boolean variable to my while loop onDuty and a public function logOff() which sets this onDuty bool to false to get me out of the run's whi...


multithreading - Java RMI: stopping a Thread running on the client machine

Suppose I have an RMI Client-Server application. Clients connect to the Server and at some point the Server starts a task. During the task Clients are doing some work, but at some other moment the Server must interrupt this work without letting the Clients finish it. Clients are implemented as Threads and the simplest solution looks like calling thread.interrupt(), but this does not work in ...


multithreading - Java Threads - Stopping a thread from running via another thread making a method call

I have a Runnable class that I'm writing. Inside of it, I have two methods. The run() method, and another method called stopRunning(). stopRunning() is to be called by a separate thread from the one that's running the run() method and is to stop the thread running the run() method from running. Here's a code snippet: public class myRunnable implements Runnable { private boolean stillRunning = t...


multithreading - Stopping a thread from another thread in a hashmap using a volatile boolean flag in java

So i have my MainThread class that is responsible for all other threads.(creating, stopping, monitoring) public class MainThread implements Runnable { public static volatile boolean keepRunning = true; public void run(){ //some code.. while(keepRunning){ //here i am creating threads for my Wired class (explaining below) //that are stored in a hashmap Wire...


multithreading - java thread - why stopping a new thread is allowed

I have a question for the below statements When a thread is a new thread, it is merely an empty Thread object. No system resources have been allocated for it yet. When a thread is in this state, you can only start the thread or stop it. Calling any method besides start or stop when a thread is in this state makes no sense and causes an IllegalThreadStateException.


multithreading - Stopping a thread when another thread has finished in java

I'm new to programming with Multi-Threading, so I don't really understand why my code is not working right. I have looked and searched on this site for answers and on google too, but did not find anything (or I did not know that it was a correct answer for me), so I'm asking you experts. I have to make the user input a number. This number will be the amount of organs in the Fibonacci that will be displayed ...


multithreading - Stopping blocking sockets in java

I have a java socket calling a server. However, I do not know at which address I can reach the server, so I put several sockets in several threads and they try to reach the server each on one address. My probem is that I do not want to wait for the timeout but have no idea how to stop the sockets and their threads properly. Code: socket = new Socket(); socket.connect(endpoint, timeout); // **Blockin...


multithreading - Java thread not stopping even when while loop is done

I have a client <-> server application. The problem is when I click a button "Exit" it does not kill the entire thread. It kills the process, but the thread still remains active. But if I click the "X" button the JOptionPane.showConfirmDialog is stopping everything, so I would like the button to do the same (to be terminated). P.P. The "Exit" button starts a JSwingWorker which is calling disconnect()


multithreading - Java BlockingQueue of Size=1?

Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue. I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want? Ex...


multithreading - HTTP posts and multiple threads in Java

I am writing an internal Java Applet to do file uploads via HTTP. I started using the built in ClientHttpRequest which worked great if I want to post one after another. When I try to have multiple threads post at the same time, something on the server side freaks out and the connection will hang for large files while still uploading the smaller files. (Large seems to be around 10 megs) After lots of looking, I would no...


multithreading - Tools for finding Shared Mutable data bugs in Java

I have a large legacy system to maintain. The codebase uses threads all over the place and those threads share a lot of mutable data. I know, sounds bad. Anyway, don't answer "rewrite the whole application from scratch" or I'll vote you down :-) I have tried to run some static analysis tools on the codebase, but none of those seem to catch this case which occurs a lot in our source code: multiple threads are reading and wr...


multithreading - synchronizing io operation in java on a string method argument?

This question already has answers here:


multithreading - Threading issues in a Java HashMap

Something happened that I'm not sure should be possible. Obviously it is, because I've seen it, but I need to find the root cause & I was hoping you all could help. We have a system that looks up latitude & longitude for a zipcode. Rather than access it every time, we cache the results in a cheap in-memory HashTable cache, since the lat & long of a zip code tend to change less often than we release.


multithreading - Firing a mainline event from a background thread in Java

My question pertains to multi-threading in Java. I'm translating an app I wrote in Visual Basic 2008 into Java. There is a class in VB called BackgroundWorker, which allows the coder to perform a task on another thread, a lot like SwingWorker in Java. The only distinct difference ...


multithreading - Java: Run a Callable in a separate process

Given an instance x of Callable<T>, how can I run x in a separate process such that I can redirect the standard input and output of the process? For example, is there a way to build a Process from a Callable? Is there a standard Executor that gives control over input and output? [UPDATE] It's not important that the Callable


multithreading - How can you ensure in java that a block of code can not be interrupted by any other thread

exampl: new Thread(new Runnable() { public void run() { while(condition) { *code that must not be interrupted* *some more code* } } }).start(); SomeOtherThread.start(); YetAntherThread.start(); How can you ensure that code that must not be interrupted won't be interrupted?


multithreading - Java while loop and Threads!

This question already has answers here:


multithreading - In Java critical sections, what should I synchronize on?

In Java, the idiomatic way to declare critical sections in the code is the following: private void doSomething() { // thread-safe code synchronized(this) { // thread-unsafe code } // thread-safe code } Almost all blocks synchronize on this, but is there a particular reason for this? Are there other possibilities? Are there any best practices on what object to sync...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top