Stopping a thread
On the previous pages, we focussed on how to
start a thread in Java. We saw that after creating the Thread object,
calling start() asynchronously starts the corresponding thread. In our example,
the run() method contained an infinite loop. But in real life, we generally
want our thread to stop. So how do we make our thread stop?
Firstly, the thing you shouldn't do is call Thread.stop().
This method, now deprecated, was intended to stop a given thread abruptly. But the problem
with this is that the caller can't generally determine whether or not the given
thread is at a safe point to be stopped. (This isn't just a Java phenomenon:
in general, the underlying operating system
calls that Thread.stop() makes to abruptly stop the thread
are also deprecated for this reason.)
So how can we stop a thread safely? In general:
To make the thread stop, we
organise for the run() method to exit.
There are a couple of ways that we would typically do so.
Use a "stop request" variable
A common solution is to use an explicit "stop request" variable, which we
check on each pass through the loop. This technique is suitable provided that we
can check the variable frequently enough:
private volatile boolean stopRequested = false;
public void run() {
while (!stopRequested) {
...
}
}
public void requestStop() {
stopRequested = true;
}
Note that we must declare the stopRequested variable
as volatile, because it is
accessed by different threads.
Use Thread.interrupt()
The above pattern is generally suitable if the variable stopRequested
can be polled frequently. However, there is an obvious problem if
the method blocks for a long time, e.g. by calling
Thread.sleep() or waiting on an object.
In general, such blocking methods are interruptible. For more
information, see the section on thread interruption.
Organise for the thread to receive a queued "stop" message
In a typical producer-consumer
pattern, where a thread blocks waiting on a queue (e.g. a
BlockingQueue), we could
organise for the thread to interpret some special object on the queue to mean
"please shut down". To ask the thread to shut down, we therefore post the
special message object to the queue. The advantage of this method is that the thread
will finish processing messages already on the queue before shutting down.
See also
Among other things, see the section on
thread safety for an introduction to some of the
measures that need to be taken to make threads safely interact with one another,
and hence why stopping a thread abruptly isn't safe.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.