Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 330
Omar Kooheji Avatar asked Oct 29 '08 16:10

Omar Kooheji


People also ask

How do you stop a thread in Java?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected.

How do you stop a thread from another thread in Java?

interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.

What are the two methods to stop threads?

Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.

How do you stop an infinite thread in Java?

The only way to stop a thread asynchronously is the stop() method.


2 Answers

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.

like image 103
Jon Skeet Avatar answered Oct 07 '22 12:10

Jon Skeet


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

like image 45
gizmo Avatar answered Oct 07 '22 13:10

gizmo