Java Concurrency Interview Question: How to timeout a thread?

Using interrupts, volatiles or AtomicBooleans to stop the thread and Thread.sleep or Schedulers for conditional timeouts.
Channel
----------------------------------
Complex concepts explained in short & simple manner. Topics include Java Concurrency, Spring Boot, Microservices, Distributed Systems etc. Feel free to ask any doubts in the comments. Also happy to take requests for new videos.
Subscribe or explore the channel - / defogtech
New video added every weekend.
Popular Videos
----------------------------------
What is an API Gateway - • What is an API Gateway?
Executor Service - • Java ExecutorService -...
Introduction to CompletableFuture - • Introduction to Comple...
Java Memory Model in 10 minutes - • Java Memory Model in 1...
Volatile vs Atomic - • Using volatile vs Atom...
What is Spring Webflux - • What is Spring Webflux...
Java Concurrency Interview question - • Java Concurrency Inter...

Пікірлер: 143

  • @abhijitsalvi4170
    @abhijitsalvi41705 жыл бұрын

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

  • @richardashton5158

    @richardashton5158

    2 жыл бұрын

    instablaster

  • @sharanyarai378
    @sharanyarai3785 жыл бұрын

    Hit like if you need more videos on interview questions. 👍

  • @gosnooky
    @gosnooky5 жыл бұрын

    Your videos have really helped me understand Java's concurrency model. Cheers!

  • @rohitsharma-xt8qe
    @rohitsharma-xt8qe4 жыл бұрын

    Honestly speaking i have never seen such an awesome explanation of this topic.

  • @Dawntech
    @Dawntech5 жыл бұрын

    This is so useful, keep up with the good work, man :) Cheers from Brazil!

  • @drakezen
    @drakezen5 жыл бұрын

    All your videos have been top quality. Please keep up the great work!

  • @propertydelver
    @propertydelver Жыл бұрын

    I've got this exact question on an interview and answered confidently: ScheduledExecutorService or CompletableFuture. I binge watched your Java Concurrency playlist the day before. Thank you so much!!

  • @DefogTech

    @DefogTech

    Жыл бұрын

    Thats so awesome to hear! Glad these videos helped

  • @visalrao4733
    @visalrao47334 жыл бұрын

    Dude..... the best explanation you can get it on youtube...Thank you so much.

  • @analogylibrary
    @analogylibrary5 жыл бұрын

    Just one word- Marvelous explanation

  • @ahadporkar7355
    @ahadporkar73554 жыл бұрын

    Very perspicuous and transparent ! Thank you 👍

  • @rohitjain1447
    @rohitjain14475 жыл бұрын

    Thanks bro! Keep making , no one can explain better than you. Cheers!!

  • @nagarajubommarapu1523
    @nagarajubommarapu15234 жыл бұрын

    Explained in a very very simplified way. Superb!

  • @manognajoshik8465
    @manognajoshik84652 жыл бұрын

    Great!! Thanks for the valuable content you provide. Understanding multithreading has not been easy always but your videos have proven to be real blessings!! Thanks a lot sir

  • @AmandeepSingh-sx9ke
    @AmandeepSingh-sx9ke5 жыл бұрын

    You explain so good . 😊 Thank you for your videos 🙏🏻❤️

  • @abhishekjm8611
    @abhishekjm86114 жыл бұрын

    Really amazing content. Hoping to see more.

  • @ibrahimshaikh3642
    @ibrahimshaikh36425 жыл бұрын

    Ur really doing great job, God bless you.

  • @amanokuba4688
    @amanokuba46885 жыл бұрын

    Sound, Video, clarity.... all 100%

  • @mohammedthahajk7619
    @mohammedthahajk76193 жыл бұрын

    haven't found a better concurrency tutorial on youtube till date Kudos

  • @giveaway4002
    @giveaway40022 жыл бұрын

    truly great. Thread.stop() got depreciated cus it can mess the program, imagine some important task is running (writing a file) in the thread and suddenly Thread.stop() is called.

  • @ArjunKumar-zu2kl
    @ArjunKumar-zu2kl4 жыл бұрын

    One word for videos is just BRILLIANT.....

  • @ILyaCyclone
    @ILyaCyclone4 жыл бұрын

    Perfectly explained!

  • @deepmingle
    @deepmingle3 жыл бұрын

    You are certainly best of a lot when it comes to content and way of explaining. Keep it up! Git url with code would be great ! Thanks.

  • @ravicrazyster
    @ravicrazyster2 жыл бұрын

    Wow. So crisp n clear

  • @pavnn2347
    @pavnn23473 жыл бұрын

    I regret that i have not seen ur videos for this long. u made hard concepts looks simple. Please do more videos if possible.

  • @ChrisAthanas
    @ChrisAthanas5 жыл бұрын

    Very well done presentation! Kudos

  • @MilanKamboya
    @MilanKamboya5 жыл бұрын

    good stuff... really liked and explained very well...

  • @anjalikumari2796
    @anjalikumari27963 жыл бұрын

    Awesome explanation..Hats off to you..

  • @deepgsingh
    @deepgsingh5 жыл бұрын

    Very organized content, Please keep creating videos

  • @vaib5917
    @vaib59175 жыл бұрын

    More such interview questions, please. Thanks

  • @dhananajaykrishna8259
    @dhananajaykrishna82593 жыл бұрын

    Best explanation..... Please post more of these 🙏

  • @GajendraSingh1990
    @GajendraSingh19905 жыл бұрын

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

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Thank you bro!

  • @prashantsharma9856
    @prashantsharma98565 жыл бұрын

    Great Work thank you so much

  • @ayanSaha13291
    @ayanSaha132912 жыл бұрын

    Thanks for content. 👍.

  • @vijaykumarreddyt3287
    @vijaykumarreddyt3287 Жыл бұрын

    Great tutorial, Dude

  • @Lucky-uz3je
    @Lucky-uz3je5 жыл бұрын

    excellent........you are awesome.

  • @satyanarayanajammala5129
    @satyanarayanajammala51294 жыл бұрын

    awesome man... keep going

  • @13success66
    @13success662 жыл бұрын

    Thanks sir sooo beautiful explanation ❣️

  • @harshadakhandekar4607
    @harshadakhandekar46074 жыл бұрын

    The theory is amazing yet simple. Best in KZread. 👍 👍 👍 Saved my life :) In my recent interviews for one of the leading investment banks , they asked me several practical coding question related to the topics you covered in this playlist. Can you please make a new video on solving such coding multi threading questions.Thanks in Advance.

  • @youngsambyun5854
    @youngsambyun58545 жыл бұрын

    thank you for this video very good !!!

  • @mingli9563
    @mingli95633 жыл бұрын

    Love this channel

  • @logicbuffer2162
    @logicbuffer21624 жыл бұрын

    Great video.

  • @deepakmarneni2110
    @deepakmarneni21105 жыл бұрын

    You are awesome. Your channel deserves more subscribers

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Thank you for your kind words sir!

  • @LivenLove
    @LivenLove5 жыл бұрын

    excellent explanation thanks.

  • @Nithin_Coorg
    @Nithin_Coorg5 жыл бұрын

    Good Explanation! Can you make video of "Hanging Thread Detection and Handling "

  • @dnbhatia85
    @dnbhatia855 жыл бұрын

    Super explained

  • @ramanapanku4306
    @ramanapanku43065 жыл бұрын

    Very knowledgeable

  • @chandra111443
    @chandra1114435 жыл бұрын

    Nice explanation

  • @rishinjiya42
    @rishinjiya423 жыл бұрын

    Hi, your explanations are out of this world. Could you please make a video on thread-safety in static methods, please?

  • @zss123456789
    @zss1234567894 жыл бұрын

    Thank you so much!

  • @ianwanjala8621
    @ianwanjala86216 күн бұрын

    very helpful tutorial

  • @babasahebgongale5006
    @babasahebgongale50063 жыл бұрын

    Super!

  • @MrAanjaneya
    @MrAanjaneya5 жыл бұрын

    Real interview question for me and failed miserably. Thanks for the video.

  • @maverick_entertainment21
    @maverick_entertainment214 жыл бұрын

    Amazing

  • @aleksandarvanced5434
    @aleksandarvanced54345 жыл бұрын

    Make more videos like this!

  • @bigheat86
    @bigheat862 жыл бұрын

    Danke!

  • @justACatOnYoutube
    @justACatOnYoutube4 жыл бұрын

    Upvote + 10 points for pointing a note on IO Operations case!

  • @traptiagrawal1214
    @traptiagrawal12143 жыл бұрын

    Thanks for your video, how can we achieve same with threads running across various jvm?

  • @balak2811
    @balak28113 жыл бұрын

    Its rather just easy to use awaitTermination for 10 mins on the the threadpool. It locks the main for 10 mins and as soon as it expires trigger the interrupts across all threads.

  • @rohitjain1447
    @rohitjain14475 жыл бұрын

    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.

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Sir, I try to make 1 video per week. I have been both busy and lazy lately :) I aim to make and upload much more frequently. Next 3-4 videos are all about java concurrency interviews. Hope they will be useful. Thank you so much for the support and love shown so far!! It helps me be motivated..

  • @anoop1341

    @anoop1341

    5 жыл бұрын

    You are amazingly good man..keep the good work up. I also started recently videos for tech content and trying to be little less lazy and hope will share the url once it's enough as of now just started but your voice and clarification and design of content is awesome.

  • @LakshmananMe
    @LakshmananMe5 жыл бұрын

    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.!!!

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Thanks buddy! I use Google Slides for presentation

  • @venkateshrajendran2362
    @venkateshrajendran23623 жыл бұрын

    Great content and explanation. A guide to Java Async programming. What in case of CompletableFuture orTimeout(long timeout, TimeUnit unit) ( or completeOnTimeout) Will the underlying thread gets canceled?

  • @chetanbhandari3033
    @chetanbhandari30332 жыл бұрын

    Bro thnx lot

  • @tusharkarkera8615
    @tusharkarkera86154 жыл бұрын

    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.?

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    Concurrency in practice is a good book.. other than that personally haven't liked any..

  • @aurojitbasak3249
    @aurojitbasak32495 жыл бұрын

    Please share more interview questions

  • @mahendharkhedhar7887
    @mahendharkhedhar78875 жыл бұрын

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

  • @apoorvanayak1736
    @apoorvanayak17362 жыл бұрын

    Great video! Suggestion for another video which is also an interview question "Implement a delayed scheduler"

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    Thank you! That's a good idea

  • @krishnapanigrahi6926
    @krishnapanigrahi69263 жыл бұрын

    Plz explain saga design pattern in microservice .Practical implementation will be much more appreciated.

  • @diegoramos27
    @diegoramos275 жыл бұрын

    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?

  • @qataracgnacgn
    @qataracgnacgn2 жыл бұрын

    Thank you for your clear and succinct explanations. Create a book with all these topics - one per chapter. I think it will sell very well. You can use the self-service LeanPub or other online publishers to create and publish your book.

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    Great suggestion! Let me think about it

  • @aakash24041990
    @aakash240419904 жыл бұрын

    @Defog Tech : Please create videos on java collections.

  • @amritabasu2243
    @amritabasu22433 жыл бұрын

    Good stuff. You dont need the keepRunning to public if you use the stop()

  • @akashagarwal6390
    @akashagarwal63904 жыл бұрын

    Damn good

  • @nikkisingh1041
    @nikkisingh10414 жыл бұрын

    how can i create a runtime class and mapped it with hibernate without adding and restarting our application please make a video on it.

  • @SurendraBabuK
    @SurendraBabuK4 жыл бұрын

    Which logic will be there in task.stop() ?

  • @gopikumar857
    @gopikumar857 Жыл бұрын

    bro.. could you do a video on Big 0 notation?

  • @tanveerengg
    @tanveerengg5 жыл бұрын

    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?

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Any thread which is waiting on IO does not occupy the CPU. It goes into waiting state and is offloaded from CPU. In case of web servers total thread count (say 200) limits number of simultaneous requests since even though CPU is free all 200 threads could be in waiting state. And threads are expensive (1-2 MB) so it's not wise to create too many of them.

  • @tanveerengg

    @tanveerengg

    5 жыл бұрын

    @@DefogTech thanks for quick reply. How to check thread size in MBs? Also of any datastructure?

  • @developerabhishek7099
    @developerabhishek70992 жыл бұрын

    Hey, can you tell me how to implement a case where multiple threads want to acquire a lock on an object and only the first one is allowed to process it. remaining threads which are waiting can be removed so that they can work on something else instead of waiting.

  • @asankasiriwardena3383
    @asankasiriwardena3383 Жыл бұрын

    Thread class does have method called stop() that can immediately stops execution of a task, but deprecated as it is inherently unsafe

  • @DefogTech

    @DefogTech

    Жыл бұрын

    It will start throwing exception now - bugs.openjdk.org/browse/JDK-8289610

  • @AbhishekVaid
    @AbhishekVaid2 жыл бұрын

    The biggest confusion I have is how to then write the Task code in a way that we are able to check for interrupts between subsequent statements of evaluations. When we write a function, we write it imperatively, focussing on the logic that we want to implement. Putting a literal if or a global while between every statement is something I've never seen anybody coding

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    In 99% of the cases you will never want to check for interrupts. It is only useful when your tasks are very long and there are reasons due to which you may want to cancel that task mid-way.

  • @chandramoulisharma4188
    @chandramoulisharma41884 жыл бұрын

    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 ?

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    Execute method returns void, submit will return future but for callable only... Not 100 percent sure, can you please check the docs

  • @windowcrystal4012
    @windowcrystal40124 жыл бұрын

    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?

  • @askalaveeska

    @askalaveeska

    4 жыл бұрын

    Me too have the same question. I feel that it is an invalid solution. Challenge for any thread to stop, is to abruptly leave the work/task whatever it was doing. It is not really an issue of stopping a iterative task after some iterations or just one iteration. May be shutdownhook helps?!

  • @ashitateotia8101
    @ashitateotia81013 жыл бұрын

    Can you please explain why while timeout we are using stop() method when this method is not supported anymore.

  • @shivendratiwari3238
    @shivendratiwari32384 жыл бұрын

    Bro why don't you create a playlist which dives deep in stream exploring all the APIs

  • @TarekFaham
    @TarekFaham Жыл бұрын

    Great video... If you use lock / unlock, how do you guarantee that the lock if acquired will be surly unlocked after say 3 seconds? This is because the caller of the class using lock/unlock may forget to unlock and in such case, we want to ensure it is going to be unlocked no matter what. How is that possible?

  • @DefogTech

    @DefogTech

    Жыл бұрын

    AFAIK there is no such API in Java. Its upto the developer to unlock, preferably in finally blocks. FWIW, if you forget to unlock, most likely you will catch that during testing itself since no other thread will be able to acquire the lock for duration of entire run.

  • @krrsss
    @krrsss5 жыл бұрын

    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?

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    correct, in that case before every step we will need to add this if condition checking for volatile or interrupt..

  • @AmitGadaley17

    @AmitGadaley17

    3 жыл бұрын

    I had the same question.

  • @shalingupta8281
    @shalingupta82814 жыл бұрын

    Can you make a video on Static and non-static synchronization, I have been asked this question many times and recruiter never seems to be happy.

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    Can you elaborate more on the question?

  • @diegoramos27
    @diegoramos275 жыл бұрын

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

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Yes, I haven't used core API for Http connection but libraries like Retrofit and Spring http client both allow you to set timeouts

  • @alsto8298
    @alsto82983 жыл бұрын

    1. There is a stop method in Thread class, but it is deprecated long ago because it is unsafe for your data to stop like that and not because "threads are cooperative in nature" 2. if (booleanValue == true) --> if (booleanValue)

  • @kumarashutosh229
    @kumarashutosh229Ай бұрын

    help me understand this, `while(keepRunning == true) { ...... }`. Once you're inside the while loop, and you have got multiple steps (say readBalance(), debitAmount(), notifySuccess()), how are you expecting that the execution will halt in between these steps and read the `keepRunning` value again, unless the loop re-iterates next time(after all the 3 steps). It will be like an infinite loop, won't it? Since, the while loop condition is checked at the `beginning of each iteration`, the loop will `continue to execute` the current iteration even after `keepRunning` becomes false. It will stop ONLLY at the beginning of the next iteration when the condition `(keepRunning == true)` is false. Correct me if I'm wrong here :) Thanks for the video!

  • @MakeItStik
    @MakeItStik2 жыл бұрын

    @Defog - should the easiest solution be to join the thread with timeout set as 10 min ? t.join(10*60*1000); This will make main thread wait for 10 mins and interrupt the spun thread ? Kindly correct if I am wrong or misunderstood the requirement

  • @slr150
    @slr1504 жыл бұрын

    What happens when your task calls a library that swallows the InterruptedException (I've seen this in certain JDBC drivers)? .

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    That's IO operation, most java IO librarues respect the interrupts but yes, it's upto the library code to handle it.

  • @ironhide9955
    @ironhide99554 жыл бұрын

    there is stop() in Thread class but its deprecated, but that would be a very simple solution.

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    It was removed purposely since if you stop the thread, the objects it was mutating can be in bad state.. since only that thread knows what should be the right state of the object, it should be allowed to change object state properly and only then stop

  • @ratneshchouhan6
    @ratneshchouhan62 жыл бұрын

    @Defog, how to handle deadlock situation and how to resolve it?

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    Simplest way is to acquire the locks in same order in all threads, that would avoid locks. If locks are based on objects then get hashCode of object, sort based on that hashCode, then acquire locks in that order.

  • @MakeItStik

    @MakeItStik

    2 жыл бұрын

    Avoid circular wait (i.e acquiring lock ) and to break circular wait you acquire locks in all threads in same sequence. T1 - lockA --> lockB T2 - lockA --> lockB

  • @AyushSharma-ux4fk
    @AyushSharma-ux4fk5 ай бұрын

    can you please share these slides?

  • @Nirdiwakar
    @Nirdiwakar4 жыл бұрын

    Or use a handler and cancelAllCallbacks

  • @prathameshchaudhari1306
    @prathameshchaudhari13062 жыл бұрын

    Need one help in one scenario. I am creating a new thread which does recursive task. After some time thread gives stack over flow error. I want to run recursive task with out giving stack overflow error. How to do it?

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    Issue is not thread related, it is about number of times the recursive task being called. Put a counter and see what the count is and when program stops printing it.

  • @MakeItStik

    @MakeItStik

    2 жыл бұрын

    StackOverflow in a recursion occurs if your exit condition is not met in any of the iterations. Exit condition helps your stack to collapse back to initial state. Try creating Euler diagram for few iterations.

  • @shankarm2848
    @shankarm28482 жыл бұрын

    Is there any way to kill a interrupted thread without using while loop?

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    nope, threads are cooperative in Java, cant kill them.

  • @081sidd
    @081sidd4 жыл бұрын

    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

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    yes, thats correct..

  • @windowcrystal4012
    @windowcrystal40124 жыл бұрын

    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.

  • @NathanJohnson815

    @NathanJohnson815

    4 жыл бұрын

    It's deprecated, meaning you shouldn't use it. And anyone reviewing your code in either an interview or real life would hopefully not let you use it ;)

  • @pratiknarkhede2027
    @pratiknarkhede20272 жыл бұрын

    Please comeback