Java Concurrency Interview Question: How to timeout a thread?

Java Concurrency Interview Question: How to timeout a thread?

so here’s an interesting Java interview
question there’s a task running in a separate thread and your job is to stop
the task if it exceeds 10 minutes so basically we have a thread let’s say the
main thread that’s going to start another thread which will actually run
the task and then after a certain time out in this case it’s 10 minutes you
want to be able to stop that particular task so let’s divide the problem into
two parts first part is how do you stop a particular thread and the second part
is how do you do it after a certain time out so let’s start with the first part
stopping a thread so let’s say we create a new thread in our main method which is
our main thread so we are going to create a new thread we are going to
submit a runnable to it and in that runnable will have all that steps which
are there in a task in this case it doesn’t matter what and then we are
going to start that particular thread once we start the thread we want to wait
for 10 minutes and then we want to stop that particular thread so to stop the
thread all we have currently is the handle of thread which is t1 so let’s
see if there are any api’s in the thread class which will help us stop the thread
and the short answer is no we do not have a stop method in the thread class
okay so we cannot really kill a thread or stop a thread so what other
alternative do we have so let’s say instead of a raw thread we can try
something else let’s try a thread pool instead so let’s
say we create a thread pool and we are going to submit our task in the form of
a runnable to that particular thread pool so now it’s thread pools
responsibility to assign a thread to that task and to run that task we will
have a time out of ten minutes we’ll discuss that later how once that ten
minutes has passed we are going to stop the task so for the thread pool we could
do either a shutdown or we could do shutdown now in an attempt to stop the
threads which are running our task so now the question is if we execute the
method shut down or shut down now does it really stop the thread if we check
the actual documentation of shutdown it says it does two things first it will
not accept any new tasks that you are going to submit to the thread pool
– whatever previously submitted tasks are there in the queue which are not yet
executed it executes them okay so it does nothing about stopping any of the
existing tasks if you use the shutdown now method it will return any of the
tasks which are waiting to be executed in the queue and any of the tasks which
are currently being run by the thread are just attempted to stop
so shutdown now does not guarantee that it will be able to stop the thread and
that is it will be able to stop our task so using even a thread pool is not going
to help us so what’s the third option maybe we could try something like a
callable instead of runnable so we’ll use the same thread pool but now instead
of submitting a runnable we’re going to submit a callable if we submit a
callable the thread pool returns us a handle in the form of a future and
future class has this method called cancel so maybe after waiting for 10
minutes if we do future dot cancel it will stop the thread but again if you
check the documentation of future it does not guarantee that it’s going to
stop the task it will only attempt to stop the thread okay so that brings us
to the first lesson which is Java threads cannot be killed okay they are
cooperative in nature so for a thread to stop someone needs to ask politely and
the way to ask the thread to stop is either using interrupts or using volatiles so let’s start with the interrupts so for using interrupts we’ll create a
new thread we’ll wait for 10 minutes and we are going to call the interrupts
method on that thread and the task itself needs to listen for the
interrupts so within the task we need a condition and if condition saying that
is the current thread interrupted if yes that means that someone wants me to stop
doing what I am doing and then it’s up to this task’s responsibility whether to
return or whether to continue in this case we know that the timeout has passed
and we want to stop the task so we’ll do a return but if we observe
closely we are doing this check only once in
between step two and step three so if our current task is between step
three and step four it won’t get an opportunity to test whether it has been
interrupted so instead we’ll use a while loop so we’ll keep checking whether the
thread is interrupted and if it is not interrupted then we’ll perform the next
steps so let’s say we have ten steps in our task after every step we are going
to check if the thread is interrupted if not we’ll continue with this step and if
the task is interrupted we’ll just come out of the while loop and the task is
finished and by default the threads job is done and it will be killed and in
fact this concept of interrupts is what is used by three other concurrent
utility in an attempt to stop the thread so we spoke about how thread pool dot
shutdown now does not guarantee the stopping of the threads and that is
because all shutdown now does is internally it will go to all the threads
and it will do a thread dot interrupt that means that even if we used the thread
pool within the thread pool task also we can apply the same concept of checking
for interrupt so when we do thread pool dot shut down now internally it will
apply the interrupt and our task will catch that interrupt it will come out of
the while loop and that particular task will be marked as complete the exact
same thing with future dot cancel so the same example that we saw earlier where
instead of a runnable we had a callable which returned the future and after
10 minutes we were attempting future dot cancel and when we have the parameter
value as true that means that whenever cancel is called internally whatever
thread is running our future related task that particular task is interrupted
so even here if we have the check for interrupts we’ll be able to come out of
the while loop and we can complete our tasks so interrupts are one of the ways
to check if some other thread wants us to stop the other way is to simply use a
volatile variable so let’s say in this example and
using Java 8 lambdas we are going to have a class called my task that
implements runnable and it overrides the run method and all the steps which are
involved in the task are mentioned here but these steps are you run only as long
as the variable keepRunning is true and this variable is public and of the type
volatile so as a task it is saying that I’ll keep running until the value of
this volatile variable is true just start a raw thread with that task and
after 10 minutes if the main thread just changes the value of this volatile from
true to false since it’s a volatile when the thread t1 reaches the while loop
again it will find the value of keep running as false and that is when it
will come out of the while loop and the run method has been completed and the
thread automatically dies and since volatiles and atomic boolean’s are very
similar we can replace this volatile with an atomic boolean and the entire
code will remain the same so either we use atomic boolean or volatile it really
doesn’t matter so in all these earlier examples we assumed that our task is
running some Java operations as a set of steps and after every step we had a
while operation where it checked for the interrupts or the volatiles and it
performed the next step but what if instead of Java operations it is doing
some IO operations so let’s say in this case our task instead of doing some Java
operation is making a stored procedure call which is a database operation and
let’s say this store procedure is very slow and it takes more than 10 minutes
in that case our thread will be stuck at this point and it will never be able to
reach the while again to check if there is an interrupt or a volatile changed
right so it’s important to confirm that it’s not an i/o operation it has to be a
Java operation so that you can keep going back to the while loop so in such
cases the libraries itself like the JDBC library and HTTP client library
they have these timeout methods where you can specify them the maximum timeout
you can wait for this operation so now that we have understood how to stop a
thread let’s go back to the second part of the question which is you want to be
able to do that only after a certain time out in this case the time out of 10
minutes and this part is relatively straightforward so the first option we
have is we start the thread and for the timeout we just say thread dot sleep for
10 minutes so this will make the main thread sleep for 10 minutes after it
wakes up we can use any of the previously discussed methods to stop our
task we can also use a scheduler service for it so here we have a scheduled
executor service where we are scheduling stopping off our task after 10 minutes
so we are saying that run this particular operation after 10 minutes
and within that operation we are saying thus not stopped and third instead of
runnable if you have a caller bill where do you get a future object even the
future object has this method called future dot get and you can give it a
duration and in this case we can guess a get me the value of this future and wait
maximum for 10 minutes if in that 10 minutes you do not get the value of the
future then there will be a timeout exception and within the timeout
exception we can use the same thing as earlier either we can use future dot
cancel or we can use the task dot stop using the volatiles so that’s it that’s
how we solve this particular question so that’s it for this video this was a very
interesting question to me if you have any similar interesting questions that
you want us to solve together please let me know in the comments thanks a lot for
watching and see you in the next one bye

52 thoughts on “Java Concurrency Interview Question: How to timeout a thread?

  1. Sir will you make a vedio on Netty server how it internally works please no good source is available in internet

  2. Can I ask the maker of the video, where were you all these days? We missed your videos for a long period. Multithreading indeed is the very advance and necessary topic in Java. We would love to get more videos. Also if you can make videos on Design patterns, it will be great.

  3. I tried something simple:

    MyTaskAtomic task2 = new MyTaskAtomic();
    Thread t2 = new Thread(task2);
    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
    ses.schedule(()->{task2.stop(); }, 10, TimeUnit.SECONDS);

    class MyTaskAtomic implements Runnable{
    public AtomicBoolean keepRunningAtomic = new AtomicBoolean(true);

    public void run() {
    while(keepRunningAtomic.get() == true) {
    System.out.println("Thread started: "+Thread.currentThread().getName());
    for(int i = 0;i<10000001;i++)
    System.out.println("inside run of MyTaskAtomic");

    public void stop() {
    System.out.println("interrupted MyTaskAtomic");

    Thread started: Thread-5
    interrupted MyTaskAtomic
    inside run of MyTaskAtomic

    If you see even after task being interrupted, it still went ahead and executed task (i mean run() method on that thread). Shouldn't it supposed to stop and not execute run() method?

  4. As always like your all other videos short, clear and easy to understand. I'm a big fan of your channel now. Hoping to learn more with your videos. Keep continuing the good work man. 😊 May I please know which tool you use to showcase the PPT? Thanks.!!!

  5. Why would you use thread.sleep() for time out logic?? that would suspend the execution of the thread right? What the question wants is for you to ask the thread to stop after 10 minutes has elapsed which you demonstrated with the ExecutorService and Future.

  6. I dont think anybody can explain the java concurrency like you. Thankyou very much brother. Keep this up.

  7. Kudos to the way the content is designed, displayed and articulately explained. Very useful for advanced developers.

  8. the way of explaining concepts in step by step manner using pictorial representations and at perfect pace is commendable. This helps to absorb things for eternity.

    You can move (What are Java interrupts?) to this playlist and Introduction to Completable future as well so that everything is avaialable under 1 umbrella.

    One question, just to confirm:
    so in web application, in case of IO operations, it may go into thread starvation as many threads at a time in server pool will be all engaged / can get busy.
    However, in case of non web applications, in case of IO operation, the moment thread goes to block state, context swithing will happen and thread will be offloaded from cpu so as to server another task / thread.
    Because many of your videos (be it async programming or webflux) revolve around point 1 eventhough second point is also correct as explained in Spinlock.
    Is this correct understanding?

  9. Is there any way to timeout the HttpRequest after a specified time ? I tried both Connection_Timeout and Read_Timeout ? thanks

  10. Hi
    I am appreciating you tutorial its fabulous .
    Any One can check below explained by running .

    as interrupt() method is handled by JVM , we can call it . but it will be effective if and only if the corresponding thread will be in either waiting state or in sleeping state . otherwise interrupt call will be no use. will never stop a thread . As i have seen in below program .
    package threadlocaldemo;

    public class ThreadInterrupteMethodTest {

    public static void main(String[] args) {

    Thread thread = new Thread(() -> {

    for(int i=0 ; i<1000; i++) {

    System.out.println(" I am very fast" +i);


    try {

    Thread.sleep(1000); //——————-1
    Thread t= new Thread();

    synchronized (t) {


    } catch (InterruptedException e) {

    System.out.println("I got interrupted");








    First run by using "————-1".and comment "————–2"
    2nd . run by "——-2" .and comment "———-1"

    ie : If a the thread either be in sleep or wait . then only interrupt will be effective , otherwise calling interrupt will be no use.

  11. 10:23, is the task required to check on isInterrupted for this implementation to work ? Or can I simply rely on future.get Timeout to be sure that the task will be cancelled if the time out has exceeded?

  12. Great video but I don't understand one thing: if we include our steps in a while loop it will go through all steps and then check the condition and repeats this over. What if we want these steps to be different from one another and be executed only once. We cant just put them in while loop can't we?

  13. For someone who is learning advanced java, your videos are one of the best resources I've found online. Appreciate your effort to put all these together. Can you recommend me some book(s) for mastering topics like concurrency, thread safety, writing multithreaded code, learning new java APIs, etc.?

  14. the way you explain this is really mind blowing. Just one question Executors.execute return the ExecutorService and Executors.submit return the Future Object, is this correct ?

  15. 1:05 you said there is not stop() method to stop the thread. But as far as I know, there is indeed a stop() but just deprecated.

  16. You are using while() loop & interrupt, but then you are assuming your code in run() method can come back to while() loop, but that does not always happen, right?

  17. So, does it mean that we can never guarantee to stop/cancel a thread at a given point of time? Please correct if I have got it all wrong

Leave a Reply

Your email address will not be published. Required fields are marked *