How to properly stop the Thread in Java?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Overview
Stopping a thread in Java is an essential concept for developers who aim to manage application resources effectively and avoid unexpected behaviors. Java provides multiple ways to control the lifecycle of a thread, each with its advantages and drawbacks. This article explores the proper techniques to stop a thread, discussing both deprecated and modern approaches, and providing practical examples for better understanding.
Thread Lifecycle
In Java, a thread can exist in different states, such as NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. Understanding these states is crucial when managing the thread lifecycle and implementing a safe shutdown process.
Deprecated Method: Thread.stop()
Explanation
Java initially provided the Thread.stop() method to halt a thread's execution. However, it was deprecated due to several reasons:
- The abrupt termination of a thread can lead to the release of locks and leave shared resources in an inconsistent state.
- It could lead to data corruption, as the execution of critical sections might be interrupted.
Example
Although deprecated, the syntax of using Thread.stop() is straightforward:
Modern Approach: Using Flags
Explanation
A safer approach is to use a control flag to signal the thread to stop. The flag is usually a volatile boolean that the thread periodically checks within its loop to decide whether it should stop executing.
Example
Explanation of the Code
- Volatile Boolean Flag: The
keepRunningflag is declared asvolatile, ensuring visibility across threads and preventing caching issues. - Graceful Termination: Interrupt status is restored by calling
Thread.currentThread().interrupt()—an important step in maintaining a thread’s interrupt loop. - Thread.sleep() is encapsulated within a
try-catchto handle interruptions properly without abruptly terminating the thread.
Using Thread.interrupt()
Explanation
The Thread.interrupt() method offers another approach to stop a thread. This method doesn't directly terminate the thread but instead signals the thread that it should pause its execution. The thread should handle InterruptedException in a way that can gracefully release resources and conclude operations.
Example
Key Points
- Checking for Interruption: The loop is controlled by the
isInterrupted()flag, allowing clean termination. - Handling
InterruptedException: Every invocation ofsleep()should be wrapped in a try-catch to catch interruptions and act appropriately.
Summary Table
| Method | Description | Pros | Cons |
Thread.stop() | Abruptly stops the thread. | Easy to implement. | Unsafe, leads to data corruption. |
| Volatile Flag | Uses a flag to let the thread exit the loop. | Safe, controlled shutdown. | Requires regular checks inside the loop. |
Thread.interrupt() | Interrupts the thread, requires handling by the thread. | Safe, allows intermediate exit. | Potentially complex exception handling. |
Best Practices
- Avoid using
Thread.stop(). - Use flags or interruption mechanisms to signal threads to terminate.
- Ensure that shared resources and locks are released properly.
- Always handle
InterruptedExceptionto reset the interrupt status and exit the thread gracefully. - Regularly check for termination signals within the thread logic to avoid hanging resources or memory leaks.
Implementing these tips ensures the robustness of your multi-threaded applications, leading to fewer bugs and better resource management. Stopping a thread safely in Java doesn't mean halting it abruptly but rather guiding it to a halt gracefully and efficiently.
Related reading
- How to put a task to sleep or delay in C 4.0?
- How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?
- How to read file with async/await properly?
- How to read in an XML file asynchronously?
- How to proxy a HTTP video stream to any amount of clients through a Spring Webserver
- How to quickly and conveniently create a one element arraylist
- How to reject in async/await syntax?
- How to rename primary key when using Debezium and Kafka Connect JDBC sink connector to synchronize databases?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.