Search

Monday, July 20, 2015

How to stop a thread in Java? Example

Today we're going to learn about how to stop a thread in Java. It's easy to start a thread in Java because you have a start() method but it's difficult to stop the thread because there is no working stop() method. Well, there was a stop() method in Thread class, when Java was first released but that was deprecated later. In today's Java version, You can stop a thread by using a boolean volatile variable.  If you remember, threads in Java start execution from run() method and stop, when it comes out of run() method, either normally or due to any exception. You can leverage this property to stop the thread. All you need to do is,  create a boolean variable e.g. bExit or bStop. Your thread should check its value every iteration and comes out of loop and subsequently from run() method if bExit is true. In order to stop the thread, you need to set value of this boolean variable to true when you want to stop a running thread. Since you are setting this variable from a different thread e.g. main thread, its important to mark this variable volatile, otherwise its possible for the running thread to cache its value and never check back to main memory for updated value and running infinitely. When you make a variable volatile, running thread will not cache its value in its local stack and always refer main memory. Volatile variable also provides happens before guarantee, which can be used to synchronize values. If you want to understand multi-threading and concurrency in right way, I strongly suggest to read Java Concurrency in Practice twice. Its one of the most accurate, thorough and practical book in Java multi-threading.
Read more »

No comments:

Post a Comment