JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

How to stop a thread in Java with Example


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. Exit or Stop. Your thread should check its value every iteration and comes out of the loop and subsequently from run() method if Exit is true. 


In order to stop the thread, you need to set the 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, it's important to mark this variable volatile, otherwise, it's 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. The volatile variable also provides happens before guarantee, which can be used to synchronize values. If you want to understand multi-threading and concurrency in the right way.



How to stop a thread in Java- An Example


Here is our sample code example to stop a thread in Java. You can see that in this example, the main thread is first starting a thread and later it's stopping that thread by calling our stop() method, which uses a boolean volatile variable to stop running thread e.g. Server.  From the output, it's clear that our Server, which implements Runnable is running fine until main() method called the stop() method, the only then value of boolean volatile variable exit is set to true. In next iteration, our Server thread checks and find this value true, so it come out of the loop and run() method, which means your thread is now stopped.

Using boolean volatile variable to stop a thread in Java





Stopping a Thread in Java - An Example

Java program to demonstrate how to stop a thread in Java using the boolean volatile variable, 




import static java.lang.Thread.currentThread;

import java.util.concurrent.TimeUnit;

/**
 * Java Program to demonstrate how to stop a thread in Java.
 * There is a stop() method in Thread class but its deprecated 
 * because of deadlock and other issue, but its easy to write
 * your own stop() method to stop a thread in Java. 
 * 
 *
 */

public class ThreadStopDemo {

    public static void main(String args[]) throws InterruptedException {
        Server myServer = new Server();

        Thread t1 = new Thread(myServer, "T1");
        t1.start();
        
        //Now, let's stop our Server thread
        System.out.println(currentThread().getName() + " is stopping Server thread");
        myServer.stop();
        
        //Let's wait to see server thread stopped 
        TimeUnit.MILLISECONDS.sleep(200);
        
        System.out.println(currentThread().getName() + " is finished now");
    }
}

class Server implements Runnable{
    private volatile boolean exit = false;
    
    public void run() {
        while(!exit){
            System.out.println("Server is running.....");
        }
        
        System.out.println("Server is stopped....");
    }
    
    public void stop(){
        exit = true;
    }
}

Output
Server is running.....
Server is running.....
Server is running.....
Server is running.....
Server is running.....
Server is running.....
Server is running.....
Server is running.....
Server is running.....
Server is running.....
main is stopping Server thread
Server is running.....
Server is stopped....
main is finished now




Things to remember:


1) Please ensure that boolean variable which is used to stop the thread is volatile, otherwise, in the worst case your thread may not stop and run infinitely, Why? because, in the absence of any synchronization instruction e.g. volatile modifier here, the compiler is free to cache the value of boolean variable exit, which means even if the main thread makes it true, Server will always see it false, thus running infinitely. .

2) It's always better to check for a boolean variable in your while loop, it could be your game loop or main server loop used to process the request.

3) It's good to provide a method to stop the server, which does nothing but changes the value of a boolean variable.

4) Using TimeUnit class to pause a thread is better than Thread.sleep() method because it improves readability. You know up front that whether the thread is stopping for 2 milliseconds or 2 second, which was not visible in case of Thread.sleep()

.